views:

77

answers:

4

I've tried looking but I haven't found anything with a definitive answer. I know my problem can't be that hard. Maybe it's just that I'm tired..

Basically, I want to declare a pointer to a 2 dimensional array. I want to do it this way because eventually I will have to resize the array. I have done the following successfully with a 1D array:

int* array;
array = new int[somelength];

I would like to do the following with a 2D array but it won't compile:

int* array;
array = new int[someheight][somewidth];

The compiler gives me an error stating that ‘somewidth’ cannot appear in a constant-expression. I've tried all sorts of combinations of ** and [][] but none of them seem to work. I know this isn't that complicated...Any help is appreciated.

+2  A: 

Read up on pointer syntax, you need an array of arrays. Which is the same thing as a pointer to a pointer.

int width = 5;
int height = 5;
int** arr = new int*[width];
for(int i = 0; i < width; ++i)
   arr[i] = new int[height];
dutt
Did you try this? It doesn't compile (if height and width are both variables)
Paul
Yes I have tried this and still get the same error with the compiler. it will say that "‘width’ cannot appear in a constant-expression"
If I were to access an element of this array would it just be arr[width][height]?
@user391369 correct.
Dave18
Awesome. Thanks for the help.
+2  A: 

A ready to use example from here, after few seconds of googling with phrase "two dimensional dynamic array":

int **dynamicArray = 0;

// memory allocated for elements of rows. 
dynamicArray = new int *[ROWS];

// memory allocated for  elements of each column.  
for( int i = 0 ; i < ROWS ; i++ ) {
    dynamicArray[i] = new int[COLUMNS];
}

// free the allocated memory 
for( int i = 0 ; i < ROWS ; i++ ) {
    delete [] dynamicArray[i];
}
delete [] dynamicArray;
ArunSaha
This is an array of arrays, not really a 2D one.
Alexander Rafferty
@Alexander Rafferty: I see -- what is the difference between "array of arrays" and "2D arrays'?
ArunSaha
+1  A: 
const int someheight = 3;
 const int somewidth = 5;

 int (*array)[somewidth] = new int[someheight][somewidth];
Tony
A: 

I suggest using a far simpler method than an array of arrays:

#define WIDTH 3
#define HEIGHT 4

int* array = new int[WIDTH*HEIGHT];
int x=1, y=2, cell;
cell = array[x+WIDTH*y];

I think this is a better approach than an array of an array, as there is far less allocation. You could even write a helper macro:

#define INDEX(x,y) ((x)+(WIDTH*(y)))

int cell = array[INDEX(2,3)];
Alexander Rafferty