【发布时间】:2016-10-23 07:19:09
【问题描述】:
我的程序有一些警告,然后它崩溃了。崩溃似乎与警告有关,但我不明白。这是我的代码:
#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)
它有什么问题?如何修复警告和崩溃?
【问题讨论】:
-
警告信息中有哪些不清楚的地方?而且您不认为段错误与您忽略警告有关吗?你知道警告很有用。你把它弄错了。首先修复警告,也许你的代码会运行,就像那样。
-
我尝试重新整理一下信息,现在我认为这个问题更具可读性和相当不错的问题。
标签: c linux struct segmentation-fault format-specifiers