0

I would like to reallocate an array of string with a function. I write a very simple program to demonstrate here. I expect to get the letter "b" to be output but I get NULL.

void gain_memory(char ***ptr) {
    *ptr = (char **) realloc(*ptr, sizeof(char*) * 2);
    *ptr[1] = "b\0";
}

int main()
{
    char **ptr = malloc(sizeof(char*));
    gain_memory(&ptr);
    printf("%s", ptr[1]); // get NULL instead of "b"
    return 0;
}

Thank you very much!

2
  • 1
    Don't cast the return of realloc, this is C after all. (Doing so might hide problems that the compiler would tell you otherwise.) Commented Apr 30, 2012 at 9:48
  • Also, don't assign the result of realloc immediately to the pointer you're reallocating. If realloc fails, you've lost the original pointer and have leaked memory. (Oh, and check for allocation failure too.) Commented Apr 30, 2012 at 10:42

3 Answers 3

3

The [] operator has high priority than *, so change the code like this will work right.

(*ptr)[1] = "b";

P.S. "\0" is unnecessary.

Sign up to request clarification or add additional context in comments.

Comments

0

You should put parentheses around *ptr in gain_memory:

(*ptr)[1] = "b\0";

Comments

-1

You're not allocating any memory for the actual strings in your array of strings, you need to do something like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void gain_memory(char ***ptr, int elem) {
    *ptr = (char**)realloc(*ptr, 2*elem*sizeof(char*));
    (*ptr)[1] = "b";
}

int main()
{
    //How many strings in your array?
    //Lets say we want 10 strings
    int elem = 10;
    char **ptr = malloc(sizeof(char*) * elem);
    //Now we allocate memory for each string
    for(int i = 0; i < elem; i++)
        //Lets say we allocate 255 characters for each string
        //plus one for the final '\0'
        ptr[i] = malloc(sizeof(char) * 256);

    //Now we grow the array
    gain_memory(&ptr, elem);
    printf("%s", ptr[1]);
    return 0;
}

1 Comment

He doesn't need to allocate the memory for the actual strings in the example since he only assigns a constant string to one of the pointers.

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.