【问题标题】:How to rectify this segmentation fault?如何纠正这种分段错误?
【发布时间】:2020-12-16 17:49:22
【问题描述】:

我的一个朋友正在学习指针概念,所以他编写了这个程序,但我不知道为什么这个程序是。它显示分段错误。我怎样才能找到这个程序中的错误?

代码如下:

#include<stdio.h>
#include<conio.h>
struct Student
{
    /* data */
    char name[20];
    int age;
    // int rollNo;
};
int main()
{
    struct Student s1;
    struct Student *ptr;
    ptr = &s1;

    scanf("%s",ptr->name);
    scanf("%d",ptr->age);
    // scanf("%d",ptr->rollNo);

    printf("%s",(*ptr).name);
    printf("%d",(*ptr).age);
    // printf("%d",(*ptr).rollNo);
return 0;
}

【问题讨论】:

  • 我觉得不错。
  • scanf("%d",ptr-&gt;age); 更改为 scanf("%d",&amp;ptr-&gt;age); 您的编译器应该对此发出警告。

标签: c pointers segmentation-fault


【解决方案1】:

当你想读取一个整数时,你需要传递一个指向 scanf 的指针,像这样:

scanf("%d", &(ptr->age));

您还需要通过检查返回值来确保输入有效,如下所示:

count = scanf("%d", &(ptr->age));
if (count == 1) {
    /*an integer was entered*/
}

当您编译 C 程序时,您应该始终启用警告。例如,GCC 编译器会告诉您有关您的原始程序的信息:

$ gcc -o test -Wall test.c
test.c: In function ‘main’:
test.c:16:10: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=]
  scanf("%d", ptr->age);
         ~^   ~~~~~~~~

【讨论】:

    猜你喜欢
    • 2015-02-25
    • 1970-01-01
    • 2010-10-18
    • 1970-01-01
    • 2016-06-23
    • 2016-07-26
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多