c++ - 指向 C++ 中的指针

标签 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;
}

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

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

最佳答案

这是根据注释和更正代码的逐步解释。

#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;
}

关于c++ - 指向 C++ 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24730437/

相关文章:

c++ - std::_Bit_rerefence& 类型的非常量引用的无效初始化

c++ - 如何从 vector<char> 复制一个整数

c - 为什么此 C 结构初始化代码会产生总线错误?

c++ - 如何在C++中从原始指针转换为唯一指针

c - 在 C 中使用带指针的模运算符

c++ - 你能帮我理解 "significant digits"在 float 学中的含义吗?

c++ - 如何在C++中实现线程

c++ - 显示指定地址的 16 个字节的内容(十六进制)

qt 5 中的 C++11 线程

c - 变量类型信息如何以及在哪里存储?