Assign Memory to 3D array using triple pointer

后端 未结 5 873
别跟我提以往
别跟我提以往 2021-01-01 05:54

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

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


        
5条回答
  •  情深已故
    2021-01-01 06:25

    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].

提交回复
热议问题