Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign Memory to 3D array using triple pointer

I have to assign memory to a 3D array using a triple pointer.

#include <stdio.h>
int main()
{
    int m=10,n=20,p=30;
    char ***z;
    z = (char***) malloc(sizeof(char**)*m*n*p);
    return 0;
}

Is this correct way of doing this?(I think what i am doing is incorrect.)

like image 834
Rog Matthews Avatar asked Dec 16 '22 23:12

Rog Matthews


2 Answers

To completely allocate a 3D dynamic array you need to do something like the following:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int m=10,n=20,p=30;
    char ***z;

    z = malloc(m * sizeof(char **));
    assert(z != NULL);
    for (i = 0; i < m; ++i)
    {
        z[i] = malloc(n * sizeof(char *));
        assert(z[i] != NULL);
        for (j = 0; j < n; ++j)
        {
            z[i][j] = malloc(p);
            assert(z[i][j] != NULL);
        }
    }
    return 0;
}

Freeing the data is left as an exercise for the reader.

like image 67
Paul R Avatar answered Dec 18 '22 13:12

Paul R


There's no need to cast the return value of malloc(), in C.

And if you expect to store m * n * p characters directly (and compute the address yourself), then you should of course not scale the allocation by the size of a char **.

You mean:

int m = 10, n = 20, p = 30;
char *z = malloc(m * n * p * sizeof *z);

This will allocate 10 * 20 * 30 = 6000 bytes. This can be viewed as forming a cube of height p, with each "slice" along the vertical axis being n * m bytes.

Since this is for manual addressing, you cannot use e.g. z[k][j][i] to index, instead you must use z[k * n * m + j * m + i].

like image 45
unwind Avatar answered Dec 18 '22 14:12

unwind