我想创建一个具有可变大小的矩阵(相同的高度和宽度),这意味着高度和宽度取决于变量。现在我知道如何使用 malloc/calloc 保留存储,但我不知道如何使用 malloc 创建二维数组。 或者有不同的方法来解决我的问题吗? 提前致谢!
最佳答案
I can't figure out how to use malloc to create a two-dimensional array.
// Example of a 2D array. malloc() cannot create this.
int TwoD[height][width];
malloc()
可以为int
、数组等分配内存。它不能创建数组。 malloc()
的结果是一个指针。因此,从指向二维数组的指针开始。
// C99, C11
int (*a)[height][width];
为a
分配内存
a = malloc(sizeof *a);
assert(a); // Insure NULL was not retuned.
使用内存
(*a)[0][0] = 1;
(*a)[0][1] = 2;
// ...
(*a)[height-1][width-1] = height*width;
完成后免费
free(a);
关于c - 如何创建可变长度的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44424013/