C中的字符串连接?

String concatenation in C?

我试图了解字符串在 C 中的行为,这让我很困扰,因为我的以下两个代码片段导致了不同的输出: (为了这个问题,让我们假设用户输入 12)

int main(void)  
{
    char L_Red[2];
    char temp[] = "I";
    printf("Enter pin connected to red: ");
    scanf("%s", L_Red);
    strcat(temp,L_Red);
    printf("%s \n", temp);
    return 0;
}

这会产生:12 作为输出(而不是 I12)为什么?

int main(void)  
{
    char L_Red[2];
    printf("Enter pin connected to red: ");
    scanf("%s", L_Red);
    char temp[] = "I";
    strcat(temp,L_Red);
    printf("%s \n", temp);
    return 0;
}

这会产生:I12I(而不是 I12)为什么?

我已经阅读了 C 中的字符串,根据我的理解,我既没有为 temp 分配任何固定大小并在以后更改它以获得这些模糊的输出,也没有像它们不应该的那样使用字符串。这里还有其他概念吗?

数组 temp 是一个包含 两个 个字符('I' 和字符串终止符 '[=13=]')的数组。而已。尝试向该数组追加更多字符将写入 越界 并导致 undefined behavior.

您需要确保目标数组 temp 有足够的 space 来容纳其原始内容 加上 您要追加的字符串(加上终结者)。


此外,如果您想为 "string" L_Red 输入多个字符,您还需要增加其大小。

我还建议您在格式说明符中使用限制,这样您就不能写越界:

char L_Red[3];  // Space for two characters, plus terminator
scanf("%2s", L_Red);  // Read at most two characters of input

您得到了奇怪的答案,因为您的目标字符串(即 strcat 的第一个参数)的长度不足以处理这两个字符串和一个空终止字符。 L_Red 的长度也太短,因为它也没有足够的 space 作为空终止字符。