I am really new to C++ programming so please pardon my silly question.
I have an array that looks like this:
double myarray [15][20000]; // Works ok but stack overflow error if I change 15 to about 200
I would like to achieve something like this:
double myarray [total][20000];
then at runtime I want user to input the value of total:
cin>>total
Please advice on how to acheive this and what is the best practice to solve this and avoid stack overflow.
Thanks.
Use a
vectorofvectors:And you can use them just like an array, and you won’t get a stack overflow:
And you can even make them bigger on the fly if you need to.
You’re getting a stack overflow because the stack is usually pretty small and you are trying to allocate too big an array on it.
vectoruses dynamically allocated memory on the free store which is usually much bigger and won’t give you an overflow error.Also, in C++ the size of static arrays must be known at compile time which is why you can’t read in a number and use that, whereas with
vectors you can resize them at runtime.