c - 段错误和 printf 警告

标签 c linux struct segmentation-fault format-specifiers

我的程序出现一些警告,然后崩溃了。崩溃似乎与警告有关,但我不明白它们。这是我的代码:

#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/

相关文章:

c - 我如何在 CFFI 中包装包含结构指针的结构?

c++ - 在结构数组上使用 C++ std::copy

c - 如何区分普通文件和符号链接(symbolic link)?

c++ - 使用 ESP Open SDK 部署到 ESP8266

linux - 使用锁定文件避免脚本的两个实例同时运行时如何避免竞争条件?

linux - 使用 bash shell 脚本锁定文件区域

c - 如何在 ANSI C 中终止一个 pthread

C 在所有接口(interface)上监听多播,响应与接收到的相同

python - 使用 pywin32/excel 在 Windows 上将 Python 移植到 Vagrant 机器上的 Linux

c - 结构表