C中连接字符串的空字节数是多少
如果我想在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
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
也是如此。