简体   繁体   English

为什么这个字符会出现分段错误?

[英]Why do I get a segmentation fault with this char?

So I'm starting to learn C, tried to make a little program to learn about structures.所以我开始学习C,试图制作一个小程序来学习结构。 It asks two "players" to enter their name and age, and then displays it back.它要求两个“玩家”输入他们的姓名和年龄,然后显示回来。

When I run it, I get a segmentation fault after entering the second player's last name.当我运行它时,我在输入第二个玩家的姓氏后出现分段错误。 I don't get why.我不明白为什么。

I tried to run it in gdb and got the following message :我尝试在gdb运行它并收到以下消息:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7e5288c in _IO_vfscanf () from /lib/x86_64-linux-gnu/libc.so.6

Here is my code, struct.c :这是我的代码struct.c

#include "struct.h"
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
  Person player[1];
  int i = 0;

  for (i = 0; i < 2; i++) {
    printf("\n=== Player %d ===\n", i+1);
    printf("First name : ");
    scanf("%s", player[i].firstName);
    printf("Last name : ");
    scanf("%s", player[i].lastName);
    printf("Age : ");
    scanf("%d", &player[i].age);
  }

  for (i = 0 ; i < 2; i++) {
    printf("\n=== Player %d ===\n", i+1);
    printf("%s %s, %d years old", player[i].firstName, player[i].lastName, player[i].age);
  }

  return 0;
}

And here is the header, struct.h :这是标题struct.h

#ifndef DEF_STRUCT
#define DEF_STRUCT
#define CHAR_SIZE 100

typedef struct Person Person;
struct Person {
  char firstName[CHAR_SIZE];
  char lastName[CHAR_SIZE];
  int age; 
};

#endif

Thanks!谢谢!

Like people told me in the comments, I replaced Person player[1] by Person player[2] .就像人们在评论中告诉我的那样,我将Person player[1]替换为Person player[2]

It now works.它现在可以工作了。

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

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