user2390934
user2390934

Reputation: 249

Pointing to pointers in c++

This piece of code no matter how hard I tried I can't understand...

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

Shouldn't this mat = new int**[4]; mean that mat would point to a int** array, so when I want to use a member of this array I should do *mat[0]?

I don't get this line mat[h] = new int*[4];.

Upvotes: 1

Views: 129

Answers (2)

sp2danny
sp2danny

Reputation: 7644

one level of 'pointership' is implicit

new int;

will give you an int*, and so will

new int[3];

move you way upwards from there

Upvotes: 0

Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7118

Here's a step-by step explanation in terms of inscribed comments and also corrected code.

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

Upvotes: 5

Related Questions