gpt4 book ai didi

c - Scrabble 小游戏程序中的 Stack smashing

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:13 26 4
gpt4 key购买 nike

下面是一个名为 scrabble.c 的程序的代码片段,该程序用于玩该游戏的简化版本。用户会收到 7 个随机字符,然后被告知使用这些字符输入一个单词。我在使用接受用户输入并将其存储在数组中的函数时遇到问题。

这个函数应该提示用户输入一个单词,然后读取它,并将它一个字符一个字符地存储在数组“word”中。该函数还应返回用户输入的单词的大小(输入的字母数)。

int read_word(char word[7], int max_size_word)
{
int c = 0, input_count = 0;
printf("Please enter your word : ");

char user_input = getchar();
for(c = 0; c < max_size_word; c++)
{
if(user_input != '\n')
{
word[input_count] = user_input;
input_count++;
printf("input_count = %d, letter entered = %c\n", input_count,
user_input);
}
else if(user_input == '\n')
{
return input_count;
}
user_input = getchar();
}
return input_count;

//错误发生在这里。错误:检测到堆栈粉碎 ./scrabble 终止中止核心转储。”

为什么检测到堆栈粉碎?

}

int main(void)
{
int t;
int letter_set[7] = {0};
char word[7];
int size_letter_set = 100;
int num_letters = 7;

generate_letter_set(&letter_set[7], size_letter_set, num_letters);
read_word(&word[7], 7);
printf("printing word : ");

for(t=0; t < 7; t++)
{
printf("%c", word[t]);
}
printf("\n");


return 0;
}

最佳答案

您可以同时调用函数:

&letter_set[7]
&word[7]

那是指向7个整型/字符数组中第8个整型/字符的指针。调用函数时只需使用 letter_setword 即可。当您的代码开始写入数组时,您的堆栈可能会崩溃。同样,函数原型(prototype)会更好:

int read_word(char word[], int max_size_word)

7 在那里没有做任何特别的事情,所以就放弃吧。

关于c - Scrabble 小游戏程序中的 Stack smashing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43337920/

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