Stupid Q regarding array
Hi,tried to define the size of an array by doing this:
and I keep getting these errors:
In the programme itself x and y would be defined by user input and the size of someArray could be anywhere from 1 to 80.All errors go when i set someArray.
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'someArray' : unknown size
Im more curious as to why it doesnt work than anything else,
Standard C++ does not support variable length arrays. Use std::vector<int> instead.
Strangely enough bought accelerated C++ and was going to make a start on it this evening and one of the first subjects is the vectors
That's probably because std::vector would be your default choice for storing variable amounts of stuff in.
Note, however, that if you used the const keyword you could declare your array as well. (But only if you are dealing with real constants whose value is known to the compiler. You can't for example get input at runtime and then create an array of that size, even if you store the entered value in a const variable.)
const int x=2;
const int y=3;
const int z=x*y;
I get you Anon.So once the compiler sees that any of the variables can change and as a result the someArray could be of any size it throws up the errors.
Normally I always knew what size the array should be so always declared haow many elements it had.
I ended up trying the code I posted because I thought it was waste of memory and what have you setting up an array with 800 elements and only using the 1st 40 or so elements.
And so thats what vectors are for:)
Thanks for the replys and explanations
You're right. It would be wastage of memory if only a few elements are used. That's why dynamic allocation of memory is used and in C++ as you said vectors are used for the same purpose.
Originally Posted by Cathalo