Nishanth_Nissy Nishanth_Nissy - 3 years ago 226
C++ Question

vector<int> a[n] allocated in stack or heap? Difference between the declarations vector<vector<int>>a(n) and vector<int>a[n]?

When I declare vector< vector< int>> a(n), memory is allocated in heap whereas when I declare it vector< int> a[n], it is allocated on stack. But why? Doesn't the second one mean the way- a[i] is a pointer to the i-th vector, as the vectors are dynamically allocated in heap and hence the whole allocation should be in heap. Isn't it?

Could you please explain me if I am wrong?

Answer Source
vector<int> adj[n];

This is not legal C++ code, you are not allowed to declare a dynamicaly sized array on the stack like this.

It's also probably the cause of your issue, as making such a huge allocation on the stack can cause some major issues.

You should use the following instead:

vector<vector<int>> adj(n);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download