加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Malloc在C中的二维数组

发布时间:2020-12-16 10:51:37 所属栏目:百科 来源:网络整理
导读:参见英文答案 A different way to malloc a 2D array?????????????????????????????????????3个 每次我为2D数组分配内存时,我首先创建一个int **数组,然后使用for我为每个元素分配内存. 例如: int ** arr = malloc(N*sizeof(int *));for(i=0; i N; i++) arr
参见英文答案 > A different way to malloc a 2D array?????????????????????????????????????3个
每次我为2D数组分配内存时,我首先创建一个int **数组,然后使用for我为每个元素分配内存.

例如:

int ** arr = malloc(N*sizeof(int *));
for(i=0; i< N; i++) arr[i] = malloc(M*sizeof(int));

不可能像以下那样分配内存:

int ** arr = malloc(N*sizeof(int[M]));

要么

int ** arr = malloc(sizeof(int[N][M]));

为了避免为?

解决方法

像这样:int(* arr)[M] = malloc(sizeof(int [N] [M]));

arr是指向int [M]的指针.

使用像arr [0] [M-1];

并且免费(arr);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读