我正在用 C 编写一个基于文本的游戏。在程序开始时,它会提示您是要开始还是结束游戏。但是,当我键入 end 或 start 时,会出现“Segmentation Fault”错误。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//Variables
char *name, *answer ;
//Beginning of program
int main()
{
//Game starts and prompts you
printf ("--|| YOUR_ADVENTURE_HERE ||-- \n") ;
printf (" \n") ;
printf ("Type 'START' to start the game or 'END' to end the game. You can end the game at any point by typing it as well.") ;
scanf ("%59s, answer") ;
//If typed 'START'
if (answer = "START")
{
printf ("\n") ;
printf ("Starting game...") ;
sleep (5) ;
return 0 ;
}
//If they typed 'END' (this will be used in every scanf)
if (answer = "END")
{
system("exit") ;
return 0 ;
}
这也是我运行它时的样子:
--|| YOUR_ADVENTURE_HERE ||--
Type 'START' to start the game or 'END' to end the game. You can end the game at any point by typing it as well.START
Segmentation fault
提前致谢!
最佳答案
在尝试在其中存储任何内容之前,先将内存分配给指针。
scanf("%59s, answer") ;
之前应该为answer
answer = malloc(60);
scanf ("%59s", answer) ;
另外,在旁注中,使用strcmp
来比较字符串。
if (answer = "START")
应该是
if (!strcmp(answer,"START"))
关于c - C 中带有 If 语句的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42917197/