简体   繁体   English

C中的字符串连接?

[英]String concatenation in C?

I am trying to understand string's behavior in C and it is bothering me since my following two code snippets result into different output: (For the sake of this question, Let us assume user enters 12)我试图理解 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;
}

this yields: 12 as output (and not I12) Why ?这产生: 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;
}

This yields: I12I (and not, I12) Why ?这产生:I12I(而不是I12)为什么?

I have read about string in C and as per my understanding, neither am I allocating temp any fixed size and changing it later to get these vague outputs nor am I using strings like the way they are not supposed to.我已经阅读了 C 中的字符串,根据我的理解,我既没有分配 temp 任何固定大小并稍后更改它以获得这些模糊的输出,也没有像他们不应该那样使用字符串。 Is there any other concept at play here ?这里还有其他概念吗?

The array temp is an array of two characters (the 'I' and the string terminator '\\0' ).数组temp是一个包含两个字符的数组( 'I'和字符串终止符'\\0' )。 That's it.就是这样。 Attempting to append more characters to that array will write out of bounds and lead to undefined behavior .尝试向该数组追加更多字符将写入越界并导致未定义行为

You need to make sure that the destination array temp have enough space to fit its original content plus the string you want to append (plus the terminator).您需要确保目标数组temp有足够的空间来容纳其原始内容加上要附加的字符串(加上终止符)。


Also, if you want to input more than one character for the "string" L_Red you need to increase its size as well.此外,如果您想为“字符串” L_Red输入多个字符,您还需要增加其大小。

I also recommend you use a limit in the format specifier so you can't write out of bounds:我还建议您在格式说明符中使用限制,这样您就不能写出越界:

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

You are getting strange answers because your destination string (ie the first argument to strcat) is not long enough to handle both strings plus a null termination character.您得到奇怪的答案是因为您的目标字符串(即 strcat 的第一个参数)不够长,无法处理两个字符串和一个空终止字符。 Also the length of L_Red is too short as it does not have enough space for the null termination character either.此外,L_Red 的长度太短,因为它也没有足够的空间容纳空终止字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM