gpt4 book ai didi

c - 增加整数和初始化放置会产生奇怪的效果吗?

转载 作者:行者123 更新时间:2023-12-04 21:56:00 26 4
gpt4 key购买 nike

我用 C 语言编写了以下“刽子手游戏”程序(写得又快又脏,所以不要太在意代码):

#include <stdio.h>

int main() {
char word[] = "cat";
int amountGuessesAllowed = 5;
size_t size = sizeof(word)-1; // -1 to exclude the '\0'

char guessedWord[size];
for (int i=0; i<size; i++){
guessedWord[i] = '_';
}

int lettersGuessed = 0;
int totalTimesGuessed = 0;
char c;

printf("%s\n", guessedWord);
printf("Guess %d - Enter a character: ", totalTimesGuessed+1);
scanf("%s", &c);

while (totalTimesGuessed < amountGuessesAllowed) {
for(int i=0; i<size; i++){
if (word[i] == c && guessedWord[i] == '_'){
printf("It matches character at index %d!\n", i);
guessedWord[i] = c;
lettersGuessed++;
printf("letters guessed: %d\n", lettersGuessed);
}
}
totalTimesGuessed++;
if (lettersGuessed == size) {
printf("You win!");
return 0;
} else if (totalTimesGuessed == amountGuessesAllowed) {
printf("You lose!");
return 0;
} else {
printf("%s\n", guessedWord);
printf("Guess %d - Enter a character: ", totalTimesGuessed+1);
scanf("%s", &c);
}
}
}

问题似乎出在 lettersGuessedtotalTimesGuessedc 三个初始化行。

如果您执行该程序并输入几个字母,您会注意到由于某种原因,totalTimesGuessed 值始终显示为 2,但它不再出现是递增的。 lettersGuessed 变量似乎没有任何问题。

___
Guess 1 - Enter a character: b
___
Guess 2 - Enter a character: c
It matches character at index 0!
letters guessed: 1
c__
Guess 2 - Enter a character: j
c__
Guess 2 - Enter a character:

现在,如果您要交换 lettersGuessedtotalTimesGuessed 的顺序,那么 lettersGuessed 变量就会出现问题(仍然是 1) !

___
Guess 1 - Enter a character: c
It matches character at index 0!
letters guessed: 1
c__
Guess 2 - Enter a character: a
It matches character at index 1!
letters guessed: 1
ca_
Guess 3 - Enter a character:

最后,如果我将 char c; 行放在两个整数之前:

char c;
int lettersGuessed = 0;
int totalTimesGuessed = 0;

然后一切都按预期进行!

___
Guess 1 - Enter a character: c
It matches character at index 0!
letters guessed: 1
c__
Guess 2 - Enter a character: a
It matches character at index 1!
letters guessed: 2
ca_
Guess 3 - Enter a character:

我已经在 Xcode 中使用 gcc 对此进行了测试。

对此必须有一个合乎逻辑的解释吗?我渴望启蒙!

最佳答案

您导致了未定义的行为

scanf("%s", &c);

因为 "%s" 说明符向目标添加一个终止 nul 字节,该目标是单个 char

相反,你可以尝试

if (scanf(" %c", &c) != 1)
handleErrorPlease();

"%c" 之前的空格是故意的,它会吃掉之前调用 scanf 留下的任何空白字符。

当发生未定义的行为时,实际发生的情况取决于程序在加载内存时的布局,因此更改已定义变量的顺序会导致行为不同。

关于c - 增加整数和初始化放置会产生奇怪的效果吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30931451/

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