分段错误:11,Absolute Beginner's Guide to C,3rd Edition Chapter6ex1.c

Sal*_*mit 0 c arrays pointers initialization

有人能告诉我为什么我会收到Segmentation错误:11.代码来自Absolute Beginner's Guide to C,3rd Edition,Chapter 6ex1.

#include <stdio.h>
#include <string.h>

main()
{

char Kid1[12];
// Kid1 can hold an 11-character name
// Kid2 will be 7 characters (Maddie plus null 0)
char Kid2[] = "Maddie";
// Kid3 is also 7 characters, but specifically defined
char Kid3[7] = "Andrew";
// Hero1 will be 7 characters (adding null 0!)
char Hero1 = "Batman";
// Hero2 will have extra room just in case
char Hero2[34] = "Spiderman";
char Hero3[25];
Kid1[0] = 'K';  //Kid1 is being defined character-by-character
Kid1[1] = 'a';  //Not efficient, but it does work
Kid1[2] = 't';
Kid1[3] = 'i';
Kid1[4] = 'e';
Kid1[5] = '\0';  // Never forget the null 0 so C knows when the
                     // string ends

strcpy(Hero3, "The Incredible Hulk");

printf("%s\'s favorite hero is %s.\n", Kid1, Hero1);
printf("%s\'s favorite hero is %s.\n", Kid2, Hero2);
printf("%s\'s favorite hero is %s.\n", Kid3, Hero3);

return 0;
}
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 5

问题开始

char Hero1 = "Batman";
Run Code Online (Sandbox Code Playgroud)

其中"Batman",(字符串文字)不是a的有效初始值设定项char.

然后,接下来,

printf("%s\'s favorite hero is %s.\n", Kid1, Hero1);
Run Code Online (Sandbox Code Playgroud)

你传递一个char代替a char *(即,指向以null结尾的数组的第一个元素的指针),因此它调用未定义的行为.

解:

  1. 启用编译器警告并收听它们.
  2. 更改char Hero1char *Hero1(如果您不打算稍后修改)或char Hero1[](否则).