字符阵列中的奇数行为
我试图为Wordle编写一个辅助程序,该程序将显示所有尚未消除的字母以及已确认的字母。我已经将程序分解为函数,并且我对 escrengeed_letters()
函数遇到了问题。
我在 Global 范围中声明了此数组:
char* word [num_letters];
它是这样初始化的:
for(int i = 0; i< num_letters; i ++)word [i] = new char(char(42));
这是函数:
void confirmed_letters() {
int num_let = 0; // the # of confirmed letters
int temp_num; // holds the position of the confirmed letter
char temp_letter;
std::cout << "\n\nHow many letters have you confirmed?\n" <<
"Enter only the letters whose positions are known. ";
std::cin >> num_let;
std::cin.ignore(1000, '\n');
if (num_let == 0) return;
std::cout << "Enter the integer position of the confirmed letter, " <<
"followed by the letter. Press the enter (return) key between each entry.\n";
for (int i = 0; i < num_let; i++) {
//temp_num = -1; // I don't think this is needed
std::cin >> temp_num;
std::cin.ignore(1000, '\n');
if (temp_num > 5 || temp_num < 1) {
std::cout << "Invalid letter position. Enter an integer between 1 and 5.\n";
i--;
goto end;
}
std::cin >> temp_letter;
std::cin.ignore(1000, '\n');
word[temp_num - 1] = &temp_letter;
end:
display_word();
}
return;
}
display> display_word( )
只是显示单词的函数。
这是我得到的输出:
How many letters have you confirmed?
Enter only the letters whose positions are known. 3
Enter the integer position of the confirmed letter, followed by the letter. Press the enter (return) key between each entry.
1
o
o * * * *
2
i
i i * * *
3
e
e e e * *
因此,出于某种原因,每个其他字母正在修改上一个字母。我不明白这里发生了什么。每当修改 word []
元素之一的值时,它应仅修改一个元素,但它正在修改所有元素。想法?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
word [temp_num -1] =&amp; temp_letter;
存储将在下一个循环迭代中重复使用的本地变量的地址,并保留用户输入的任何新值。旧价值将丢失,因此看起来所有使用的插槽都将相同的字母存储。因为他们这样做。更糟糕的是,该变量在函数末尾不在范围内,并且将不再有效。这很危险,因为。解决方案:不要将指针存储到
word
中。自己存放字母。这样的初始化:
存储
word[temp_num - 1] = &temp_letter;
stores the address of a local variable that will be reused on the next loop iteration and hold whatever new value the user inputs. The old value will be lost, so it'll look like all of the used slots store the same letter. Because they do. Worse, the variable goes out of scope at the end of the function and will no longer be valid. This is dangerous as the pointer lives on and might even give what looks to be correct results.Solution: Don't store pointers to letters in
word
. Store the letters themselves.Initialize like this:
and store