C++ in the heap to open up and release 2d 3d pointer in detail

  • 2020-04-02 01:36:16
  • OfStack

Learning C++ novices usually have a headache on the use of Pointers, in fact, the concept of Pointers is very simple, as long as you can understand such a simple reason to have a certain understanding of Pointers: for example, int *a = new int[10]; One dimensional pointer is actually equivalent to one dimensional array, do not have to read the first address of the array in memory in the book these obscure words, and so on two dimensional pointer is equivalent to two dimensional array, the novice is more familiar with the opening and release of one dimensional array, such as the above a release is delete []a; A = NULL; Notice that a = NULL; You have to add it in order to avoid the pointer becoming a wild pointer. Write procedures must pay attention to standardization and rigor, to avoid possible errors.


//Two - dimensional pointer development and release
int **b = NULL;
b = new int*[10];
for(int i = 0; i != 10; ++i)
{
     b[i] = new int[50];
     memset(b[i], 0, sizeof(int)*50);
}
//In this way, a two-dimensional pointer of int type is created on the heap, with the size of 10*50, which is equivalent to a binary stack array int b[10][50] on the heap.
for(int i = 0; i != 10; ++i)
{
     delete []b[i];
     b[i] = NULL;
}
delete []b;
b = NULL;

//Development and release of 3d pointer
int ***a = NULL;
a = new int**[10];
for(int i = 0; i != 10; ++i)
{
    a[i] = new int*[50];
    for(int j = 0; j != 50; ++j)
    {
        a[i][j] = new int[30];
        memset(a[i][j], 0, sizeof(int)*30);
    }
}
//In this way, a 3d pointer of int type is created on the heap, with the size of 10*50*30, which is equivalent to a two-dimensional array int a[10][50][30] on the stack.
for(int i = 0; i != 10; ++i)
{
    for(int j = 0; j != 50; ++j)
    {
       delete []a[i][j];
       a[i][j] = NULL;           
    }
    delete []a[i];
    a[i] = NULL;
}
delete []a;
a = NULL; 


Related articles: