使用三重指针将内存分配给3D数组 [英] Assign Memory to 3D array using triple pointer
本文介绍了使用三重指针将内存分配给3D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须使用三重指针将内存分配给3D阵列.
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.)
推荐答案
要完全分配3D动态数组,您需要执行以下操作:
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.
这篇关于使用三重指针将内存分配给3D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文