[cs13001] Dynamically allocated multidimensional array

Mikhail Nesterenko mikhail at cs.kent.edu
Thu Apr 18 16:10:20 EDT 2013


> 
> You asked me to remind you to see if you could dynamically
> allocating memory as such.
> 
> int *p;
> p=new int [5][5];
> 

As stated, it is not legal. However, there is a way to do something
like this. You need to declare "p" to be an array of pointers, then
each individual pointer will point to a single dimensional array and
the whole construction would comprise a multidimensional array. Here
is an example:


int main(void){

  const int RANGE=5;

  int (*p)[RANGE];   // declaring an array of pointers
      		     // parentheses around the asterisk are necessary
		     // because it is lower precedence than square brackets

  p = new int[RANGE][RANGE];  // allocates an integer array for every 
                              // pointer in the array of pointers

  for(int i=0; i < RANGE; i++)
    for(int j=0; j < RANGE; j++)
      p[i][j] = 55;   // this array of pointers is treated 
                      // as two-dimensional array
}


More information about the cs13001 mailing list