c++ - The correct way to initialize a dynamic pointer to a multidimensional array? -
this question has answer here:
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];
new int[4];calls operator new function()- allocates memory 4 integers.
- returns reference memory.
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:

to free memory
for 1 dimensional array,
// need use delete[] operator because used new[] operator delete[] p; //free memory pointed p;`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
Post a Comment