簡體   English   中英

C - 如何在 realloc() 之后添加到字符數組的末尾

[英]C - how to add to the end of a char array after realloc()

我有一個名為“array”的短字符數組。 我正在嘗試為其重新分配更多空間,然后在末尾添加更多字符。 出於某種原因,當我打印數組時,這些額外的字符沒有顯示出來,盡管當我單獨索引它們時它們確實顯示了。

#include <stdio.h>
#include <stdlib.h>
int main(){
    char *array = malloc(2);
    array[0] = 'b';
    array[1] = '\0';
    char stringToAdd[] = "honey";
    array = realloc(array, (16));
    int pos;
//add stringToAdd into array one char at a time
    for (pos = 0; pos < 5; pos++){
        array[2+pos] = stringToAdd[pos];
        printf("%d ", 2+pos);
        printf("%c ", array[2+pos]);
        printf("%s\n", array);
    }
    array[pos] = '\0';
    int k = sizeof(array);
//should print out the string "bhoney" and its length
    printf("%s, length = %d\n", array,k);
    free(array);
    return 0;
}

輸出是:

2 h b
3 o b
4 n b
5 e b
6 y b
b, length = 8

此外,無論我嘗試重新分配多少空間,數組的長度似乎都是 8?

您在空終止符之后添加了字符。 打印字符串在空值處停止。

將新字符分配給array[1+pos]而不是array[2+pos] 這也適用於在循環后添加新的空終止符,它應該是

array[1+pos] = '\0';

您還可以使用strcat()代替循環:

strcat(array, stringToAdd);

它將自動找到空終止符,因此您不必知道偏移量,並正確添加新的空終止符。

sizeof(array)是指針的大小(8 字節),而不是字符串的長度。 如果你想要字符串長度,你應該使用strlen(array) 查看c 中 sizeof 和 strlen 之間的區別

它應該是:

for (pos = 0; pos < 5; pos++){
    array[1+pos] = stringToAdd[pos];
    printf("%d ", 1+pos);
    printf("%c ", array[1+pos]);
    printf("%s\n", array);
}
array[1+pos] = '\0';

暫無
暫無

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

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