我正在尝试创建一个刽子手游戏但是我的程序在进入for循环时会一直崩溃。我还在阅读关于指针的内容并且完全不理解它们。我知道你不能修改字符串文字,所以我尝试制作可修改的数组,但我很确定崩溃与此有关。任何人都可以指出崩溃的具体原因吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main(int argc, char **argv)
{
char word[15];
char *wordState = malloc(15);
char *guess[1];
int guesses = 6;
int i;
printf("Enter word.\0");
scanf("%s",word);
strcpy(wordState, "---------------");
do{
printf("Please guess a letter.\0");
printf("You have %d\n guesses.\0", guesses);
scanf("%s\n",guess);
printf("%s\n", wordState);
for(i=0; word[i] != '\0'; i++)
{
if(*guess[1]==word[i])
{
strcpy(*wordState[i],*guess[1]);
}
else
{
guesses--;
}
}
}while(guesses != 0);
free(wordState);
答案 0 :(得分:4)
大多数情况下,你的问题是因为,
strcpy(wordState, "---------------");
因为你没有足够的空间来复制\0
并且基本上会造成内存溢出。
再次,使用<{1}}这样的定义,使用
char *guess[1];
if(*guess[1]==word[i])
数组基于C
。 [想想:为什么你想要1元素数组?] 我还可以注意到其他一些问题,例如
0
应为void main(int argc, char **argv)
int main(int argc, char **argv)
malloc()
应为scanf("%s",word);
,以避免更长的输入可能导致缓冲区溢出。答案 1 :(得分:0)
简化猜测,处理多次看到的信件
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
void main(int argc, char **argv)
{
char word[16];
char *wordState = malloc(16 * sizeof(char));
char guess;
int guesses = 6;
printf("Enter word.\n");
scanf("%s",word);
strcpy(wordState, "---------------");
do{
bool found = false;
printf("Please guess a letter.\n");
printf("You have %d guesses.\n", guesses);
scanf(" %c", &guess);
for(int i=0; word[i] != '\0'; i++)
{
if(word[i] == guess)
{
wordState[i] = guess;
found = true;
}
}
if (!found)
{
guesses--;
}
printf("%s\n", wordState);
} while(guesses != 0);
free(wordState);
}