簡體   English   中英

多少個空字節,在C中串聯字符串

[英]how many null bytes, concatenating strings in C

如果我想在C中連接2個字符串,我是否必須為每個字符串分配一個額外的null字符,或者一個就足夠了?

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個空字節。 有人可以照亮嗎? 謝謝

不,您不需要兩個額外的空字節。

在內存中,您的字符串將如下所示:

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'

只需要一個。

在您鏈接的問題中,它們實際上還添加了一個額外的空格字符,該字符需要一個額外的字節。

最后的字符串應以空字節結尾,因此一個就足夠了。

編輯:您發送的問題,兩個字符串之間有一個空格。

strcpy(both, first);
strcat(both, " ");
strcat(both, second);

只需要一個。 在字符串的末尾,您始終只需要一個空字符,這恰好是兩個字符串的串聯。

在您鏈接到的問題中,在串聯在一起的字符串之間放置一個空格。 必須為此空間分配一個額外的char

在您的示例中,您沒有在字符串之間放置空格,因此僅需要一個額外的char

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM