在C语言中将字符附加到字符数组中

我想将一个字符附加到表示String的字符数组中。 我使用Struct来表示String。

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

你在整个结构target上使用realloc,你应该这样做:

 target->c= (char*) realloc (target->c, newSize * sizeof(char));