I'm trying to create a pointer to char pointer to which I can easily add new elements (strings). I use malloc to create the first 2 dimensions and realloc when I want to add new items. I wrote code with and without realloc and I'm getting the same results. Is this an expected/normal behavior?
With realloc:
char **p; // create pointer to char pointer
p = malloc(sizeof(char*) * 2); // allocate 2 dimensions
p[0] = "ab";
p[1] = "cd";
void* resizedP = (void*)realloc(p, sizeof(char*) * 4); // resize array
p = (char**)resizedP;
p[2] = "ef";
p[3] = "gh";
printf("%s \n", p[0]); // prints ab
printf("%s \n", p[1]); // prints cd
printf("%s \n", p[2]); // prints ef
printf("%s \n", p[3]); // prints gh
free(p);
Without realloc:
char **p;
p = malloc(sizeof(char*) * 2);
p[0] = "ab";
p[1] = "cd";
p[2] = "ef";
p[3] = "gh";
printf("%s \n", p[0]); // prints ab
printf("%s \n", p[1]); // prints cd
printf("%s \n", p[2]); // prints ef
printf("%s \n", p[3]); // prints gh
free(p);