[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

2-D arrays in C++



Hi all-
This question is not directly related to game development, but I ran across
it while working on my game and I thought others might find it useful, so
here goes:

How do you dynamically allocate a 2-D array in c/c++?

For a one dimensional array you can do something like...
int *x;
x=new int[6];
x[2]=3;

So, for a two dimensional array I would like to do something like...
int **x;
x=new int[6][4];
x[2][1]=3;

This does not work though, because new int[6][4] has a return type of
int(*)[4] not int**.

Any ideas?

-Brett
p.s.  I know there are work arounds such as this:
int *x;
int width=6;
x=new int[width*4];
x[2*width+1]=3;

or something like this:
int **x;
x=new int*[6];
for(int i=0;i<6;i++) x[i]=new int[4];
x[2][1]=3;

What I'm looking for is the correct way to handle the return type from new
int[6][4].