指向c ++中的指针

use*_*934 1 c++ pointers

这段代码无论我怎么努力我都无法理解......

#include <iostream>

using namespace std;

int main()
{
    int ***mat;

    mat = new int**[4];

    for(int h = 0; h < 4; h++) {
        mat[h] = new int*[4];
    }

    for (int i = 0; i < 4; i++) {
        delete[] mat[i];
        delete[] mat;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这不应该mat = new int**[4];意味着mat会指向一个int**数组,所以当我想使用这个数组的成员时我应该这样做*mat[0]吗?

我不明白这一行mat[h] = new int*[4];.

Dr.*_*ana 5

以下是关于内容注释和更正代码的逐步解释.

#include <iostream>
using namespace std;
int main()
{
    int ***mat; // placeholder for a 3D matrix, three dimensional storage of integers
    // say for 3d matrix, you have height(z-dimension), row and columns
    mat = new int**[4]; // allocate for one dimension, say height
    for(int h = 0; h < 4; h++) {
        mat[h] = new int*[4]; // allocate 2nd dimension, say for rows per height
    }
    // now you should allocate space for columns (3rd dimension)
    for(int h = 0; h < 4; h++) {
       for (int r = 0; r < 4; r++) {
          mat[h][r] = new int[4]; // allocate 3rd dimension, say for cols per row
    }}
    // now you have the matrix ready as 4 x 4 x 4 
    // for deallocation, delete column first, then row, then height
    // rule is deallocate in reverse order of allocation
    for(int h = 0; h < 4; h++) {
       for (int r = 0; r < 4; r++) {
          delete [] mat[h][r]; // deallocate 3rd dimension, say for cols per row
       }
       delete [] mat[h]; // deallocate 2nd dimension, rows per height
    }
    delete [] mat; // deallocate height, i.e. entire matrix
    return 0;
}
Run Code Online (Sandbox Code Playgroud)