Ang*_*ber 3 c multidimensional-array
我无法从2个变量创建2D数组(例如,int arr[i][j]不允许),那么我将如何创建动态大小的2D数组?
数组的维度仅在我的程序中在运行时已知.该数组用于表示网格.我将如何在C中编码?
Sta*_*ven 11
首先分配一个指针数组
/* size_x is the width of the array */
int **array = (int**)calloc(size_x, sizeof(int*));
Run Code Online (Sandbox Code Playgroud)
然后分配每列
for(int i = 0; i < size_y; i++) {
/* size_y is the height */
array[i] = (int*)calloc(size_y, sizeof(int));
}
Run Code Online (Sandbox Code Playgroud)
您可以使用访问元素array[i][j].释放内存的顺序相反:
for(int i = 0; i < size_y; i++) {
free(array[i]);
}
free(array);
Run Code Online (Sandbox Code Playgroud)
你必须分配一维数组:
int* array = calloc(m*n, sizof(int));
Run Code Online (Sandbox Code Playgroud)
并像这样访问它:
array[i*n + j]
Run Code Online (Sandbox Code Playgroud)
编译器在访问二维数组时完成此操作,并且可能n在编译时猜到时输出相同的代码.