用C表示If语句的指针

rob*_*a05 2 c pointers if-statement

我正在用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 ;  
}   
Run Code Online (Sandbox Code Playgroud)

以下是我运行时的外观:

--|| 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
Run Code Online (Sandbox Code Playgroud)

提前致谢!

VHS*_*VHS 9

在尝试存储任何内容之前,将内存分配给指针.

scanf ("%59s, answer") ;

应该先为内存分配 answer

answer = malloc(60);
scanf ("%59s", answer) ;
Run Code Online (Sandbox Code Playgroud)

另外,在旁注中,用于strcmp比较字符串.

if (answer = "START")

应该

if (!strcmp(answer,"START"))


wal*_*lyk 5

问题出在这里:

scanf ("%59s, answer");
Run Code Online (Sandbox Code Playgroud)

首先,scanf需要一个参数列表来写入从输入中获得的值.你没有提供任何.相反,你只有一个长字符串.你的意思当然是:

scanf ("%59s", answer);
Run Code Online (Sandbox Code Playgroud)

但即使这样也行不通.

它需要answer分配某种内存,而不是未初始化的指针.这会更好:

char answer [60];
scanf ("%59s", answer);
Run Code Online (Sandbox Code Playgroud)

我没有进一步了解其他问题.