2

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.

2
  • 3
    You're getting stack overflow errors because the array is too big for the stack. You should allocate it on the heap instead (best done with a vector, as Seth shows). Also, variable-length arrays are not part of standard C++ IIRC. That's another plus for vectors. Commented May 1, 2012 at 19:28
  • ya, Seth example solved the problem. Thank you :) Commented May 1, 2012 at 19:54

1 Answer 1

4

Use a vector of vectors:

int total;

cin >> total;

//                                      (1)                        (2)
std::vector<std::vector<double>> myVec(total, std::vector<double>(20000));
// (1) is the first dimension and (2) is the second dimension

And you can use them just like an array, and you won't get a stack overflow:

myVec[0][4] = 53.24;
cout << myVec[0][4];

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. vector uses 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.

Sign up to request clarification or add additional context in comments.

1 Comment

A vector of std::array (equivalently the 3rd-party boost::array pre-0x) is a better match for what OP described, but not necessarily what OP really wants.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.