[C++] Const Expression

So I'm creating a function to put info into an array. Problem being is that I don't know the size of the array I'll need, so I decided to just temporarially make an array. I however don't want to have wasted space, so I decided to do this:

 
int array[wLength/length];


That failed because the division problem is not constant. So I tried:

1
2
const int temp=wLength/length;
int array[temp];


It still didn't like it. Claims it not to be constant.

So how can I make the size of the array wLength/length?

Using MSVC++ in XP.

Thanks!
Use new and delete.

int* array = new int[wLength/length];
If you are more advanced switch to vectors; you will be able to add and remove elements at will.
I honestly don't know why that doesn't work though. However keep in mind that the division itself is, as noted, not a constant expression because the values of the participants can change.
EDIT: OK, good point, you can just dynamically allocate the array.
Last edited on
Thanks everybody. I've gone with firedraco's way. I'd tried new before, but my syntax was slightly off.
As for vectors, I've never used them, but for what I've seen while looking at them, they would be too much code for what I'm doing.

Thanks again!
Actually, std::vectors are probably better than arrays for most situations. What exactly is the problem with using them?
I'm finding where things are in a string, and returning the location. Since C++ doesn't have a function for that, I'm making it. So for the one that finds all the locations, I have to return an array with all the locations in them.

So I was planning on putting the info into an array, finding the size of the array when it was done, creating a new array that is the correct size, and deleting the old one. So not to take more memory then needed.

What do you think, vectors, or an array?
vector would definitely be better.
All you would need to do is use push_back for every location, which saves you the time of deleting and allocating new memory.
Okay, I'll look further into them. After I posted that it worked, it didn't. It compiled, but the program froze at that line.

Thanks for the help. Hopefully I won't be posting in the future about vectors. :)
Topic archived. No new replies allowed.