c++ - The correct way to initialize a dynamic pointer to a multidimensional array? -


i've been having bad luck with dynamic pointers when range them 2 dimensions , higher. example want pointer 2d array. know that:

int a[3][4]; int (*p)[4] = a; 

is legit (even if don't understand why). taking consideration that:

int *p = new int[4]; 

works, imagined that:

int **p = new int[5][7]; 

would work, it's not. code states error:

error: value of type "(*)[7]" cannot used initialize entity of        type "int **" 

by seeing new part becomes pointer array of 7 integers made:

int (*p)[4] = new int[7][4]; 

and work it's not want accomplish. doing i'm limited @ least using constant value subsequent dimension, want defined @ run time , therefore "dynamic".

how go , make multidimensional pointer work??

let's start basic examples.

when int *p = new int[4];

  1. new int[4]; calls operator new function()
  2. allocates memory 4 integers.
  3. returns reference memory.
  4. to bind reference, need have same type of pointer of return reference do

    int *p = new int[4]; // created array of integer                      // should assign pointer-to-integer 

for multi-idimensional array, need allocate array of pointers, fill array pointers arrays, this:

int **p; p = new int*[5]; // dynamic `array (size 5) of pointers int`  (int = 0; < 5; ++i) {   p[i] = new int[10];   // each i-th pointer pointing dynamic array (size 10)   // of actual int values } 

here looks like:

enter image description here

to free memory

  1. for 1 dimensional array,

     // need use delete[] operator because used new[] operator delete[] p; //free memory pointed p;` 
  2. for 2d array,

    // need use delete[] operator because used new[] operator for(int = 0; < 5; ++i){     delete[] p[i];//deletes inner array of integer; }  delete[] p; //delete pointer holding array of pointers; 

avoid memory leakage , dangling pointers!


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -