gpt4 book ai didi

c - 有多少空字节,在 C 中连接字符串

转载 作者:太空宇宙 更新时间:2023-11-04 05:20:52 25 4
gpt4 key购买 nike

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

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);
}

this问题,他们为每个字符串使用 2 个空字节。有人可以阐明一些吗?谢谢

最佳答案

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

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

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'

关于c - 有多少空字节,在 C 中连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8986341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com