Dynamic allocation of multi-dimensial arrays

Hello, does anybody know how to dynamicly allocate multi-dimensial arrays? This dosent seem to work:
1
2
3
4
5
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:

1
2
3
4
5
    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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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<height; ++h)
    {
         rows[h]= new int[row_length]; //set the row itself
    }


    for(unsigned h=0; h<height; ++h)
    {
         delete[] rows[h]; //free the row
    }
    delete[] rows; //free the pointers to each row
}


Allocation and deallocation must be done in this order.
1
2
3
4
5
6
7
8
9
10
11
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.