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!

laurent
  • 88,262
  • 77
  • 290
  • 428
ldo
  • 91
  • 1
  • 6
  • 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.) – Jens Gustedt Apr 30 '12 at 09: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.) – jamesdlin Apr 30 '12 at 10:42

3 Answers3

3

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

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

P.S. "\0" is unnecessary.

Sylvester
  • 51
  • 3
0

You should put parentheses around *ptr in gain_memory:

(*ptr)[1] = "b\0";
smichak
  • 4,716
  • 3
  • 35
  • 47
-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;
}
David
  • 29
  • 2
  • 8
  • 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. – JeremyP Apr 30 '12 at 10:00