2

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); 
    }
1
  • 2
    Try realloc(target->c, newSize * sizeof(char));. Besides, you can't write to target->c[newSize], the last array cell of the string is target->c[newSize-1]. Commented Sep 19, 2013 at 9:40

1 Answer 1

2

You're apllying realloc on your whole structure target, you should do :

target->c= (char*) realloc (target->c, newSize * sizeof(char));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.