字符数组的奇怪行为

Odd behavior from character array

我正在尝试为Wordle编写一个帮助程序,它将显示所有未删除的字母和已确认的字母。我已将程序分解为函数,confirmed_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_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[] 的其中一个元素的值时,它应该只修改一个元素,但它正在修改所有元素。想法?

word[temp_num - 1] = &temp_letter; 存储将在下一次循环迭代中重复使用的局部变量的地址,并保存用户输入的任何新值。旧值将丢失,因此看起来所有使用过的插槽都存储相同的字母。因为他们这样做。更糟糕的是,变量在函数结束时超出范围,将不再有效。这很危险,因为 the pointer lives on and might even give what looks to be correct results.

解决方案:不要在 word 中存储指向字母的指针。自己存储字母。

char word[NUM_LETTERS]; 

像这样初始化:

for (int i = 0; i < NUM_LETTERS; i++) word[i] = '*'; 
    // use the character not the code. It's easier to understand the intent of 
    // * than the number 42 and not all systems will use 42 for *.

并存储

word[temp_num - 1] = temp_letter;