c - C 中带有 If 语句的指针

标签 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 ;  
}   

这也是我运行它时的样子:

--|| 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/

相关文章:

c - 指针和指针位置之间的区别

c - 指针作为调用 scanf 的函数的参数

pointers - golang 和指针接收器中的自定义错误

shell - 如何比较Makefile中的两个shell命令输出?

java - Java 中 if/else 循环中的变量问题

c# - If-Else 语句在 while 循环中不起作用

c - 独特的哈希函数,无任何冲突

python - pip 为 python 3.4 安装 igraph : compiler error

c - 仅在不使用调试器时出现段错误

c - 如何在给定指针数组的情况下创建字符串数组?