在C语言中向字符数组追加字符

在C语言中向字符数组追加字符,c,arrays,C,Arrays,我想在表示字符串的字符数组中附加一个字符。 我使用一个Struct来表示字符串 struct String { char *c; int length; int maxLength; }String; realloc正在打乱我的阵列;当我打印字符串时,它会打印内存中的随机内容。 我觉得做realloc会丢失对字符串的引用 void appendChar(String *target, char c) { printf

我想在表示字符串的字符数组中附加一个字符。 我使用一个Struct来表示字符串

struct String
{   
    char *c;  
    int length;   
    int maxLength;  

}String;
realloc正在打乱我的阵列;当我打印字符串时,它会打印内存中的随机内容。 我觉得做realloc会丢失对字符串的引用

    void appendChar(String *target, char c)
    {
        printf("\String: %s\n", target->c); // Prints the String correctly.     

        int newSize = target->length + 1;
        target->length = newSize;

        if(newSize > target->maxLength)
        {
           // Destroys my String.
            target->c= (char*) realloc (target, newSize * sizeof(char));
            target->maxLength = newSize;
        }


        target->c[newSize-1] = ch;
        target->c[newSize] = '\0';

        printf("String: %s\n", target->c); 
    }

您正在对整个结构应用realloc
target
,您应该:

target->c= (char*) realloc (target->c, newSize * sizeof(char));
尝试
realloc(target->c,newSize*sizeof(char))。此外,您不能写入
target->c[newSize]
,字符串的最后一个数组单元格是
target->c[newSize-1]