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!
realloc, this is C after all. (Doing so might hide problems that the compiler would tell you otherwise.)reallocimmediately to the pointer you're reallocating. Ifreallocfails, you've lost the original pointer and have leaked memory. (Oh, and check for allocation failure too.)