Maximum number of elements an array can hold

I have a program where it asks the user to input the number of elements of an array(I use array instead of std::vector on purpose), when I input the number 999999(6 digits)
 
  double x[999999];

the program crashes, if I input the number 99999(5 digits), it works fine.

I have googled this but I found nothing that explains this behaviour.

Any idea why this happens??
Last edited on
Memory for automatic variables is allocated from stack. Stack tends to have limited size. Sounds like you ask for more memory than what the stack has in your system.

The std::vector allocates memory from a heap. Heap has no artificial limit.
@keskiverto so in another system the program could have a diferent behavior??
so in another system the program could have a diferent behavior?

Yes, or even if you just increase the stack size on your system.
But in general you shouldn't be storing megabytes of data on the stack.
If you don't want to use a vector you can dynamically allocate the memory yourself (preferably using a std::unique_ptr or std::shared_ptr). But there's really not much advantage in that. So your best bet is probably:

 
std::vector<double> x(999999);

Last edited on
You can also put the array in initialized storage by declaring it static:
static double x[999999];
This changes the behavior slightly: the array will be zero-initialized and it will maintain its value between calls to the function.

I use array instead of std::vector on purpose

If you use the array above, what happens when the user asks for 1000000 elements?

No matter how big you make the array, the user can always ask for one more. And if you make it ridiculously huge, then you're wasting lots of space if they only need 20 items. This is why an array is a bad idea. Fundamentally you want an array whose size is determined at runtime. That's what vector's are for.
Thank you guys for your insights!!
Topic archived. No new replies allowed.