【发布时间】:2018-11-07 16:18:07
【问题描述】:
这是代码。函数“leggi”应该读取 c[i].a 的值,但是当我在控制台中输入第一个数字时,程序崩溃了。 这可能是一个指针问题,但我无法弄清楚
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct cane{
int a;
}cane;
void leggi(cane *c[20]){
int i;
for(i=0;i<5;i++)
scanf("%d", &c[i]->a );
}
int main(){
int i;
cane c[20];
leggi(&c);
for(i=0;i<5;i++)
printf("%d",c[i].a);
return 0;
}
【问题讨论】:
-
&c是指向cane[20]的指针。cane *c[20]是一个包含 20 个指向cane的指针的数组。 -
对于
C中的数组,数组名称c已经是一个指针,因此无需将&c传递给leggi(...) -
GCC 说:
error: passing argument 1 of ‘leggi’ from incompatible pointer type [-Werror=incompatible-pointer-types]——leggi(&c);——note: expected ‘cane **’ {aka ‘struct cane **’} but argument is of type ‘cane (*)[20]’ {aka ‘struct cane (*)[20]’} -
好的,谢谢! @cleblanc
-
@cleblanc
c是不是指针。但它确实衰减为指针。