有人能告诉我为什么会出现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;
}
答案 0 :(得分:5)
问题以
开始char Hero1 = "Batman";
其中"Batman"
,(字符串文字)不是char
的有效初始值设定项。
然后,接着,
printf("%s\'s favorite hero is %s.\n", Kid1, Hero1);
您传递char
代替char *
(即指向以空终止的数组的第一个元素的指针),因此它会调用undefined behavior。
<强>解决方案:强>
char Hero1
更改为char *Hero1
(,如果您不打算稍后修改)或char Hero1[]
(否则)。 答案 1 :(得分:1)
您的编译器显然已损坏。如果不为您提供诊断,则不允许符合C的编译器编译此代码。
我强烈建议抛弃你正在使用的任何编译器,并切换到符合GCC的兼容编译器。或者,如果您使用的是GCC,请正确配置。
GCC设置为标准C编译器gcc -std=c11 -pedantic-errors
提供以下诊断:
int main (void)
。char Hero1 = "Batman";
无效C,您可能需要撰写char Hero1 []
。答案 2 :(得分:0)
修正了它。
使用gcc 6ex1.c -o 6ex1
6ex1.c:10:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main()
^
6ex1.c:21:7: warning: incompatible pointer to integer conversion initializing 'char' with an
expression of type 'char [7]' [-Wint-conversion]
char Hero1 = "Batman";
^ ~~~~~~~~
6ex1.c:36:47: warning: format specifies type 'char *' but the argument has type 'char' [-Wformat]
printf("%s\'s favorite hero is %s.\n", Kid1, Hero1);
~~ ^~~~~
%c
我将char Hero1 = "Batman"
更改为char Hero1[] = "Batman"