C语言中二维数组如何申请动态分配内存

如题所述

1、使用malloc函数,先分配第一维的大小,然后再循环分配每一维的大小。

2、例程,分配3行4列二维数组:

#include <stdio.h>
#include <malloc.h>
int main()
{
    int **a;
    int i, j;
    a = (int**)malloc(sizeof(int*)*3);//为二维数组分配3行
    for (i = 0; i < 3; ++i){//为每列分配4个大小空间
        a[i] = (int*)malloc(sizeof(int)*4);
    }
    //初始化
    for (i = 0; i < 3; ++i){
        for (j = 0; j < 4; ++j){
            a[i][j] = i+j;
        }
    }
    //输出测试
    for (i = 0; i < 3; ++i){
        for (j = 0; j < 4; ++j){
            printf ("%d ", a[i][j]);
        }
        printf ("\n");
    }
    //释放动态开辟的空间
    for (i = 0; i < 3; ++i){
        free(a[i]);
    }
    free(a);
    return 0;
}
/*
输出:
0 1 2 3
1 2 3 4
2 3 4 5
*/

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-05-06
//---------------------------------------------------------------------------

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef int em_type; //数组元素的数据类型

em_type **new_mat(int rows,int cols) //新建一个行数为rows,列数为cols的二维数组,并返回首地址
{
em_type **rt=NULL;
int i;
assert((rt=malloc(sizeof(em_type *)*rows))!=NULL) ;

for (i=0; i<rows; i++)
assert((rt[i]=malloc(sizeof(em_type)*cols))!=NULL);

return rt;
}

void delete_mat(em_type **s,int rows) //删除由new_mat()函数创建的有rows行的二维数组s,释放其占用的空间
{
int i;
for (i = 0; i<rows; i++) free(s[i]);
free(s);
}
int main(void)
{
int i,r=5;
int j,c=6;
em_type **fa;

//示例,新建一个有r行c列的二维数组。
fa=new_mat(r,c);

//对fa数组进行赋值
for (i = 0; i<r; i++) {
for (j=0; j<c; j++) {
fa[i][j]=i*j;
}
}

//读取fa数组中的元素
for (i = 0; i<r; i++) {
for (j=0; j<c; j++) {
printf("%d ",fa[i][j]);
}
putchar('\n');
}

//使用完毕,删除数组,释放空间
delete_mat(fa,r);
return 0;
}
//---------------------------------------------------------------------------追问

表示看不懂,没这么长的吧

追答

表示汗一下,单纯的动态分配二维数组确实没有这么长,程序中标的很清楚,动态分配二维数组的工作都是在new_mat()这个函数中完成的,其它的函数都是为了演示new_mat()的用法,delete_mat()函数是为了回收动态分配的二维数组占用的空间。

因此,如果只是动态分配二维数组,只要明白new_mat()函数即可,即如下部分:

em_type **new_mat(int rows,int cols) //新建一个行数为rows,列数为cols的二维数组,并返回首地址
{
em_type **rt=NULL;
int i;
assert((rt=malloc(sizeof(em_type *)*rows))!=NULL) ;

for (i=0; i<rows; i++)
assert((rt[i]=malloc(sizeof(em_type)*cols))!=NULL);

return rt;
}

相似回答