Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a pointer to multidimensional array and allocating the array

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.

like image 404
vince88 Avatar asked Oct 11 '10 07:10

vince88


People also ask

How do you declare a pointer to a two-dimensional array?

The name of the array arr is a pointer to the 0th 2-D array. Thus the pointer expression *(*(*(arr + i ) + j ) + k) is equivalent to the subscript expression arr[i][j][k]. We know the expression *(arr + i) is equivalent to arr[i] and the expression *(*(arr + i) + j) is equivalent arr[i][j].

How do you declare a pointer to an array?

int *var_name[array_size]; Declaration of an array of pointers: int *ptr[3]; We can make separate pointer variables which can point to the different values or we can make one integer array of pointers that can point to all the values.

How is a multidimensional array defined in terms of an array of pointers?

An element in a multidimensional array like two-dimensional array can be represented by pointer expression as follows: **a+i+jIt represent the element a[i][j]. The base address of the array a is &a[0][0] and starting at this address the compiler allocates contiguous space for all the element row-wise.


1 Answers

const int someheight = 3; const int somewidth = 5;  int (*array)[somewidth] = new int[someheight][somewidth]; 
like image 66
Tony The Lion Avatar answered Sep 23 '22 19:09

Tony The Lion