简体   繁体   English

C中的分段错误(核心转储)

[英]Segmentation fault (core dumped) in C

Code attached below.下面附上代码。 I tried to run the code, the values printed are correct but getting segmentation fault.我尝试运行代码,打印的值是正确的,但出现分段错误。 Can anyone explain why?谁能解释为什么?

#include <stdio.h>

typedef struct
{
    char name[30];
    int age;
} rec[2];

void main()
{
    rec g;
    rec *pt = &g;

    for (int i = 0; i < 2; i++)
    {
        printf("Enter name: ");
        scanf("%s", &pt[i]->name);
        printf("Enter age: ");
        scanf("%d", &pt[i]->age);
    }

    printf("Name\tAge\n");
    for (int i = 0; i < 2; ++i)
    {
        printf("%s\t", pt[i]->name);
        printf("%d\n", pt[i]->age);
    }

Output :输出 输出

And also please explain the difference between也请解释两者之间区别

typedef struct {
    int a;
} example[3];

example v;

and

typedef struct {
    int a;
} example;

example v[3];

  1. void main() is wrong. void main()是错误的。 It has to be int main(void)它必须是int main(void)
  2. Here you have an example why hiding arrays behind the typedefs is a very bad habit.这里有一个例子,为什么将数组隐藏在 typedef 后面是一个非常糟糕的习惯。 In your case pt[1] references the next array of two structs which outside the array bounds.在您的情况下, pt[1] 引用了数组边界之外的两个结构的下一个数组。 You invoke undefined behaviour which can result in segfault.您调用可能导致段错误的未定义行为。

You need to:你需要:

typedef struct
{
    char name[30];
    int age;
} rec[2];

int main()
{
    rec g;
    rec *pt = &g;

    for (int i = 0; i < 2; i++)
    {
        printf("Enter name: ");
        scanf("%s", pt[0][i].name);
        printf("Enter age: ");
        scanf("%d", &(pt[0][i].age));
    }

    printf("Name\tAge\n");
    for (int i = 0; i < 2; ++i)
    {
        printf("%s\t", pt[0][i].name);
        printf("%d\n", pt[0][i].age);
    }
}

The best way is to typedef struct and define the array.最好的方法是 typedef struct 并定义数组。

typedef struct
{
    char name[30];
    int age;
} rec;

int main()
{
    rec pt[2];

    for (int i = 0; i < 2; i++)
    {
        printf("Enter name: ");
        scanf("%s", pt[i].name);
        printf("Enter age: ");
        scanf("%d", &(pt[i].age));
    }

    printf("Name\tAge\n");
    for (int i = 0; i < 2; ++i)
    {
        printf("%s\t", pt[i].name);
        printf("%d\n", pt[i].age);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM