Let The User Specify Array Size

I am not sure why I am receiving the error message:
error C2466: cannot allocate an array of constant size 0

When I run the code:
1
2
3
4
	int s;
	cout<<"Enter the size:\n";
	cin>>s;
	int array[s];

C++ masters, please help me.
It sounds like to me some error checking needs to be taken place. It is impossible to have an array that is less than or equal to 0 (would not make sense to have an array with said sizes anyways) so a check needs to be done to make sure that int s is greater than 0.
I do actually have will implement a loop because the input can not be less than 0 or greater than 50. But, if the program will not even run, what is the point?
You cannot create an array using a non-const int variable.

The size of an array must be known at compile time, if this does compile it's non-standard behavior.

Alternatives:
1. Use an std::vector. Does memory allocation for you. See: http://www.cplusplus.com/reference/vector/vector/
2. Use new and delete[] - this allows for dynamic storage of memory, it's basically what a vector does. (Really though, use a vector)

dynamic array ex:
1
2
3
4
5
cin >> size;
int* arr = new int[size];
//do stuff with arr
doSomethingWith( arr[some_index] );
delete [] arr;


vector ex:
1
2
3
4
5
cin >> size;
std::vector<int> v(size);
// do stuff with v
doSomethingWith( v[some_index] );
// no need to call delete or anything, it's done for you 
Last edited on
I thought that in the normal C standard you were capable of letting the user directly ask for the space he/she wanted. I might of been thinking of something else or something. Thanks for that insight though Ganado.
I don't know much about C standards, sorry. I doubt it though. You're welcome.
If I recall, I think it was capable of being done, but was frowned upon.
Thanks Ganado, got it to work.
Topic archived. No new replies allowed.