Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C中连接字符串的空字节数是多少_C_String_Malloc_Strcat - Fatal编程技术网

C中连接字符串的空字节数是多少

C中连接字符串的空字节数是多少,c,string,malloc,strcat,C,String,Malloc,Strcat,如果我想在C中连接两个字符串,我是否必须为每个字符串分配一个额外的空字符,或者一个就足够了 int main(){ char *s1 = NULL; char *s2 = NULL; char *s1_s2 = NULL; s1 = malloc(sizeof(char) * strlen("string1") + 1); strcpy(s1, "string1"); s2 = malloc(sizeof(char) * strlen("stri

如果我想在C中连接两个字符串,我是否必须为每个字符串分配一个额外的空字符,或者一个就足够了

int main(){
    char *s1 = NULL;
    char *s2 = NULL;
    char *s1_s2 = NULL;

    s1 = malloc(sizeof(char) * strlen("string1") + 1);
    strcpy(s1, "string1");
    s2 = malloc(sizeof(char) * strlen("string2") + 1);
    strcpy(s2, "string2");

    s1_s2 = malloc(sizeof(char) * (strlen(s1) + strlen(s2)) + 2); // shouldn't it be only 1 null char ?
    strcpy(s1_s2, s1);
    strcat(s1_s2, s2);
}
有问题的是,它们对每个字符串使用2个空字节。有人能给我们一些启示吗?
谢谢

最后一个字符串应该以空字节结尾,这样一个就足够了

编辑: 您发送的问题,在两个字符串之间有一个空格

strcpy(both, first);
strcat(both, " ");
strcat(both, second);
只需要一个


在您链接的问题中,他们实际上还添加了一个额外的空格字符,需要额外的字节。

只需要一个。您总是只需要在字符串的末尾添加一个空字符,这里正好是两个字符串的串联

不,您不需要额外的两个空字节

在内存中,字符串将如下所示:

s1 -> 's' 't' 'r' 'i' 'n' 'g' '1' '\0'

s2 -> 's' 't' 'r' 'i' 'n' 'g' '2' '\0'

s1_s2 -> 's' 't' 'r' 'i' 'n' 'g' '1' 's' 't' 'r' 'i' 'n' 'g' '2' '\0'

在您链接到的问题中,在连接在一起的字符串之间放置了一个空格。必须为此空间分配一个额外的
char


在您的示例中,字符串之间没有空格,因此只需要一个额外的
char

所有字符串只需要一个额外的字节,因为只有一个字符串终止符。在您的示例中,
s1\u s2
也是如此。