gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:08:32 25 4
gpt4 key购买 nike

我正在用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com