CS50 (pset2) - 在打印出首字母的 C 程序中无法理解的行为

CS50 (pset2) - Behavior not understood in C program that prints out initials

我以前有使用 Python 的经验,但在 C 方面绝对是初学者。我正在研究 CS50x pset2 initials(不太舒服),其中应该有一个简单的 C 程序接受用户给定的名字并打印出名字的首字母

当我 运行 程序时,它似乎适用于某些情况,但对于某些名称,它在末尾附加了错误的 'B' 字符。这是代码:

#include <stdio.h>
#include <cs50.h>
#include <string.h>

string get_initials(string name, char initials[]);

int main(void)
{
    // user input (full name)
    printf("Please type your name: ");
    string name = get_string();

    // get the user name initials
    char initials[10];
    get_initials(name, initials);  // in: full name; out: initials
    printf("Initials: %s\n", initials);

}

string get_initials(string name, char initials[])
{
    int counter = 0;

    // Iterate over all characters
    for (int i = 0, n = strlen(name); i < n; i++)
    {
        // in case the i-th char is ' ', appends next char to the initials array
        if (name[i] == ' ')
        {
            initials[counter] = name[i+1];
            counter++;
        }
        // appends the first char to the initials array
        else if (i == 0)
        {
            initials[counter] = name[i];
            counter++;
        }
    }
    return initials;
}

这里是一些终端输出:

~/workspace/pset2/ $ ./initials
Please type your name: John Smith
Initials: JSB
~/workspace/pset2/ $ ./initials
Please type your name: John Smith Here
Initials: JSH
~/workspace/pset2/ $ ./initials
Please type your name: John
Initials: J
~/workspace/pset2/ $ ./initials
Please type your name: John Smith Here Again
Initials: JSHAB
~/workspace/pset2/ $ ./initials
Please type your name: John Smith Here Again Where
Initials: JSHAW
~/workspace/pset2/ $ ./initials
Please type your name: John Smith Here Again Where Here
Initials: JSHAWH
~/workspace/pset2/ $ 

I debugged for "John Smith" 但仍然不明白为什么要附加 S00B 而不是 S .

get_initials函数的最后,终止字符串:

...
initials[counter] = '[=10=]';
return initials;