在C中分配2D数组 [英] Malloc a 2D array in C
本文介绍了在C中分配2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每次我为2D数组分配内存时,我都会先创建一个int**
数组,然后使用for来为每个元素分配内存.
Every time I allocate the memory for a 2D array first I create an array of int**
and then with a for I allocate the memory for each element.
例如:
int ** arr = malloc(N*sizeof(int *));
for(i=0; i< N; i++) arr[i] = malloc(M*sizeof(int));
不可能像这样分配内存:
Wouldn't be possible allocate the memory like:
int ** arr = malloc(N*sizeof(int[M]));
或
int ** arr = malloc(sizeof(int[N][M]));
为了避免for
?
推荐答案
像这样:int (*arr)[M] = malloc(sizeof(int[N][M]));
arr
是int[M]
的指针.
像arr[0][M-1];
和free(arr);
这篇关于在C中分配2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文