指向c ++中的指针

时间:2014-07-14 06:11:39

标签: 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];

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

一个级别的指针&#39;隐含的是

new int;

将为您提供int*

也是如此
new int[3];

从那里向上移动