C语言无法打印信息,struct student相关编译错误如何修复?
C代码编译错误修复:结构体类型不完整问题
编译错误信息
arrow.c:3:23: 警告:在参数列表内声明的'struct student'在该定义或声明外部不可见 void printInfo(struct student s1); ^~~~~~~ arrow.c: In function 'main': arrow.c:13:15: error: type of formal parameter 1 is incomplete printInfo(s1); ^~ arrow.c: At top level: arrow.c:18:6: error: conflicting types for 'printInfo' void printInfo(struct student s1){ ^~~~~~~~~ arrow.c:3:6: note: previous declaration of 'printInfo' was here void printInfo(struct student s1);
原代码
void printInfo(struct student s1); struct student { int roll; float cgpa; char name[100]; }; int main(){ struct student s1 = {1664, 9.2, "shradha"}; printInfo(s1); return 0; } void printInfo(struct student s1){ printf("student information ; \n"); printf("student.roll = %d\n", s1.roll); printf("student.name = %s\n", s1.name); printf("student.cgpa = %f \n ", s1.cgpa); s1.roll = 4558; }
问题原因
函数printInfo的声明放在了struct student定义之前,编译器处理函数声明时,还不知道struct student的具体结构,会将其视为不完整类型,导致后续调用函数和定义函数时出现类型不匹配、冲突的错误。
修复方案
将struct student的定义移至函数声明之前,确保编译器在处理函数声明时已经知晓结构体的完整类型。
修复后的代码
struct student { int roll; float cgpa; char name[100]; }; void printInfo(struct student s1); int main(){ struct student s1 = {1664, 9.2, "shradha"}; printInfo(s1); return 0; } void printInfo(struct student s1){ printf("student information ; \n"); printf("student.roll = %d\n", s1.roll); printf("student.name = %s\n", s1.name); printf("student.cgpa = %f \n ", s1.cgpa); s1.roll = 4558; }
内容的提问来源于stack exchange,提问作者Ayush Kumar
相关产品推荐
相关产品推荐

