[英]scanf of struct makes program crash
this is the code. 这是代码。 the function "leggi" is supposed to read the value of c[i].a but when I type the first number in the console the program crashes. 函数“ leggi”应该读取c [i] .a的值,但是当我在控制台中键入第一个数字时,程序将崩溃。 It's probably a pointers issue but i can't figure it out 这可能是指针问题,但我无法弄清楚
#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;
}
You pass the wrong type to the function. 您将错误的类型传递给函数。
If you want to pass an array to a function the array name decays to a pointer to its first element, therefore the argument is only a pointer to the type: 如果要将数组传递给函数,则数组名称会衰减为指向其第一个元素的指针,因此参数仅是指向类型的指针:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct cane{
int a;
}cane;
void leggi(cane *c){
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;
}
The type of &c
is cane (*)[20]
ie a pointer to an array. &c
的类型是cane (*)[20]
即指向数组的指针。 You've declared the argument of the function to be cane *[20]
which is (as a function argument) a cane**
which is a pointer to a pointer. 您已将函数的参数声明为cane *[20]
,它(作为函数参数)是cane**
,它是指向指针的指针。
You may have intended to pass a pointer to an element of the array instead: 您可能打算将指针传递给数组的元素:
void leggi(cane *c)
// ...
scanf("%d", &c[i].a );
//
leggi(c);
Or possibly you really intended to pass a pointer to the array instead: 或者,您可能真的打算将指针传递给数组:
void leggi(cane (*c)[20])
scanf("%d", &(*c)[i].a )
//
leggi(&c);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.