I want to Append a character to a character array which represents a String. I am using a Struct to represent the String.
struct String
{
char *c;
int length;
int maxLength;
}String;
realloc is messing up my array; when I print my string, it prints random things from memory. I feel that I am losing the reference to my string by doing 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->c, newSize * sizeof(char));. Besides, you can't write totarget->c[newSize], the last array cell of the string istarget->c[newSize-1].