C语言如何给用函数二维数组动态赋值

如题所述

1、当成普通数组使用,用for循环即可赋值。
2、例程:
#include

#include

int
main(void)
{
int
*a=NULL;
int
i;
a=malloc(sizeof(int)*10);/*动态创建一个有10个int元素的数组*/
if
(a==NULL)
{
/*a==NULL表示空间分配失败*/
fprintf(stderr,"MEMORY
ERROR");
return
-1;
}
for
(i
=
0;
i
<
10;
i++)
{
a[i]=i;
/*对数组进行赋值操作*/
}
free(a);/*动态分配的空间需要用free()函数释放*/
return
0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-04-05
二维数组名不能直接传给二级指针,应该按以下方式使用:
int nChoose;
scanf("%d", &nChoose); // 让用户输入二维数组的大小
int **a = (int **)malloc(nChoose * sizeof(int *));
for (int i = 0; i < nChoose; i ++)
{
a[i] = (int *)malloc(nChoose * sizeof(int));
}
Scan(a, nChoose);
Calc(a, nChoose);
// 最后要释放数组,也要循环本回答被提问者采纳
第2个回答  2020-03-14
二维数组名不能直接传给二级指针,应该按以下方式使用:
int
nChoose;
scanf("%d",
&nChoose);
//
让用户输入二维数组的大小
int
**a
=
(int
**)malloc(nChoose
*
sizeof(int
*));
for
(int
i
=
0;
i
<
nChoose;
i
++)
{
a[i]
=
(int
*)malloc(nChoose
*
sizeof(int));
}
Scan(a,
nChoose);
Calc(a,
nChoose);
//
最后要释放数组,也要循环
相似回答