在 C 中分配一个二维数组 [英] Malloc a 2D array in C

查看:26
本文介绍了在 C 中分配一个二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我为二维数组分配内存时,我首先创建一个 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?

推荐答案

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

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

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

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

free(arr);

这篇关于在 C 中分配一个二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆