+ 6

Creating multidimensional array on the heap

What is the right way to create a mutlidimensional array in C on the heap. Suppose I want an array with dimension 100x90x80 int arr[100][90][80]; would create it on the stack. How can I create it on the heap so I can use it the same way (as if it was on the stack). Should i use malloc? In what way? (I can't cast the returned pointer without getting compile error). Or new? How to correctly deallocate it?

8th May 2019, 7:54 PM
michal
13 Respostas
+ 2
So it is not possible in a more nice way? It is quite long with the loops. Maybe flatenning the array would be a better way?
9th May 2019, 6:01 PM
michal
+ 2
rudolph flash True, but imagine having a 3D or 4D array. Three nested loops only to allocate it. How is it with performance/speed? Are flat arrays any faster or not?
9th May 2019, 6:16 PM
michal
+ 2
~ swim ~ 1D v=vector<int>(8) 2D v=vector<vector<int>>(8, vector<int>(8)) 3D //three times 'vector' v=vector<vector<vector<int>>>(8, vector<vector<int>>(8, vector<int>(8))) //6 times vector In order to get nD vector, you have to write 'vector<' n*(n+1)/2 times.
10th May 2019, 6:03 PM
michal
0
~ swim ~ Thanks. So 1D could really be better (at least for writing the code). If using vectors with given size, it requires 'quadratic' length of code, doesn'it it a=vector vector vector int (9, vector vector int (8, vector int(7))) You have 3+2+1 times vector. This function grows quadratically :)
9th May 2019, 7:45 PM
michal