【发布时间】:2021-04-26 20:09:02
【问题描述】:
如果我将二维数组声明为
#include <stdio.h>
#include <stdlib.h>
int main() { int c=5;int r=6;
int **a=(int **) malloc (c*sizeof(int *));
int i,j;
for (i=0;i<c;i++){
*(a+i)=(int *) malloc (r*sizeof (int));
}
}
上述程序运行成功。
#include <stdio.h>
#include <stdlib.h>
int main() { int c=5;int r=6;
int **a;
**a=(int **) malloc (c*sizeof (int *));
int i,j;
for (i=0;i<c;i++){
*(a+i)=(int *) malloc (r*sizeof (int));
}
}
但是编译器在上面的程序中显示错误。
为什么会这样?任何帮助将不胜感激。
【问题讨论】:
-
提到的错误是什么?
-
第二个应该是
a=(int **) malloc(c*sizeof (int *));,或者最好是a=malloc(c*sizeof(*a));。 -
这里
int **a;和这里**a =的星号不一样。 -
分解原来的
int **a = (int **)malloc(c * sizeof(int *));,int **a = ...声明a的类型为int **,... a=(int **)malloc(...);初始化a。
标签: arrays c pointers dynamic-memory-allocation dereference