I want to have an array of strings and dynamically increase its' size when needed. Have a look at a rough piece of code:
int main(void) {
char **array_of_strings = malloc(sizeof(*array_of_strings));
func(array_of_strings);
// Lost track
}
void func(char **array_of_strings) {
array_of_strings = realloc(array_of_strings, 2, sizeof(*array_of_strings));
}
My array_of_strings in main seems to lose track of the array_of_strings after realloc. I'm aware that realloc can potentially free the original memory and move it to somewhere else entirely. What would be the best way to keep track of realloced memory in my main in this case?
My current thoughts:
Return the realloced pointer:
- I think this is bad because I'm implementing several layers of functions and it will be a huge pain to constantly have to return the realloced pointer
Additional pointer in main to keep track of realloced pointer
int main(void) {
char **array_of_strings = malloc(sizeof(*array_of_strings));
char *TRACKER = malloc(sizeof(*TRACKER));
TRACKER = array_of_strings; // Make this keep track of array of strings
func(array_of_strings, TRACKER);
}
void func(char **array_of_strings, char *TRACKER) {
array_of_strings = realloc(array_of_strings, 2, sizeof(*array_of_strings));
TRACKER = array_of_strings;
}
I think this would work??? Not sure though. But if it does work, it still seems like a hassle to keep track of an additional pointer.
Is there something I'm obviously missing like perhaps another way to malloc additional memory for arrays of strings? Or is C just annoying like this : (