### Dynamic allocation of multi-dimensial arrays

Hello, does anybody know how to dynamicly allocate multi-dimensial arrays? This dosent seem to work:
 ``12345`` ``````void blah_blah(int x, int y) { int *foo = NULL; foo = new int[x][y]; }``````
Sorry if I am being an idiot, but I always assumed that this would work fine... Also, how would I then free them, like this? `delete[][] foo`
Last edited on
You could use `new int[x][y]`, but only if `y` is a constant expression:

 ``12345`` `````` const int y = 10; int x = 10; int (*a)[y] = new int[x][y]; // do stuff with a[0][0] .. a[9][9] delete[] a;``````

But in practice, if you're working with 2D data, pick a matrix library (boost or eigen or whatever), or write your own if it's something simple. When you write your own matrix class, you can use a 1D vector of size x*y for storage, or anything else you like.

Alternatively, you could allocate an array of pointers, and set each pointer to the first element of a different, individually allocated array -- that's a common C idiom, which is equivalent to the vector of vectors in C++.
Last edited on
The correct way is to use `foo=new int[x*y];`
and `delete [] foo`
 ``123456789101112131415`` ``````void sample(const unsigned row_length, const unsigned height) { int **rows= new int*[height]; //set the pointer to reach row for(unsigned h= 0; h

Allocation and deallocation must be done in this order.
 ``1234567891011`` ``````int **pointer = new int *[range of elements] // this allocates a pointer to a pointer which points to an array. //now to allocate a two dimensional array for (int i = 0; i < (size of array); i++) { pointer[i] = new int[range of elements] // each index of the variable // pointer points to an array // whatever elements you put //above } ``````

i wish i can show you with a picture but i going to user words and you draw it out.

|box| ---------- |box|box|box| // those lines is an arrow

now draw an arrow from EACH of the three boxes and let EACH arrow point to more boxes. |box|box|box|

thats whats happening in the code above. now you can use the variable pointer that i used above as a two dimensional array

pointer[1][1] = 2;
pointer[2][2] = 4; etc

Last edited on
Topic archived. No new replies allowed.