我的程序出现一些警告,然后崩溃了。崩溃似乎与警告有关,但我不明白它们。这是我的代码:
#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 is\n%s\t%d\t%s\t%f\t%c",W[0].name,W[0].id,
W[0].department,W[1].res.gpa,W[0].res.grade);
printf("\nSecond student data is\n%s\t%d\t%s\t%f\t%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 is\n%s\t%d\t%s\t%f\t%c",
W[0].name, W[0].id, W[0].department, W[0].res.gpa, W[0].res.grade);
printf("\nSecond student data is\n%s\t%d\t%s\t%f\t%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 *
。
关于c - 段错误和 printf 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40200537/