我的程序有一些警告,然后它崩溃了。事故似乎与警告有关,但我不理解。这是我的代码:
#include <stdio.h>
struct student {
char name[100];
int id;
char *department;
struct result {
float gpa;
char grade;
} res;
};
int main(void) {
struct student W[] = {{"Saud Farooqui",137,"Electronics",{3.05,'A'}},
{"Talha Farooqui",129,"Civil",{3.5,'A'}}};
printf("First student data isn%st%dt%st%ft%c",W[0].name,W[0].id,
W[0].department,W[1].res.gpa,W[0].res.grade);
printf("nSecond student data isn%st%dt%st%ft%c",W[1].name,W[1].id,
W[1].res.gpa,W[1].res.grade);
}
编译器在第二个printf
:中打印了这些关于格式说明符的警告
foo.c:24:10: warning: format '%s' expects argument of type 'char *', but argument 4 has type 'double' [-Wformat=]
W[1].res.gpa,W[1].res.grade);
^
foo.c:24:10: warning: format '%f' expects argument of type 'double', but argument 5 has type 'int' [-Wformat=]
foo.c:24:10: warning: format '%c' expects a matching 'int' argument [-Wformat=]
当我尝试启动程序时,第一个printf
打印了一行,但第二个失败了:
Segmentation fault (core dumped)
它怎么了?如何修复警告和崩溃?
department
缺少参数。很明显,当你编译打开警告(-Wall
(:
a.c:21:7: warning: format ‘%s’ expects argument of type ‘char *’, but argument 4 has type ‘double’ [-Wformat=]
W[1].name, W[1].id, W[1].res.gpa, W[1].res.grade);
^
a.c:21:7: warning: format ‘%f’ expects argument of type ‘double’, but argument 5 has type ‘int’ [-Wformat=]
a.c:21:7: warning: format ‘%c’ expects a matching ‘int’ argument [-Wformat=]
此外,您的第一个printf
打印的W[1].res
可能是W[0].res
。
固定版本:
struct student W[] = {{"Saud Farooqui",137,"Electronics",{3.05,'A'}},
{"Talha Farooqui",129,"Civil",{3.5,'A'}}};
printf("First student data isn%st%dt%st%ft%c",
W[0].name, W[0].id, W[0].department, W[0].res.gpa, W[0].res.grade);
printf("nSecond student data isn%st%dt%st%ft%c",
W[1].name, W[1].id, W[1].department, W[1].res.gpa, W[1].res.grade);
因此,分段错误是由于试图将W[1].res.gpa
解释为指向字符串(对应于%s
格式说明符(的指针,即const char *
。