An array of pointers of chars is not getting changed in main
.
Here's the situation: Inside main
, an array of pointers of chars is declared and memory is allocated for it. main
calls another function called AddItems
which adds items to the list and that function calls doubleSize
to double the size of the list. Everything is working as expected in terms of adding new items inside AddItems
and doubling the size of the array. However, the problem is that when AddItems
returns, main still has an older copy of the list, even though we're passing a pointer to the list.
Here's a MWE:
#define INITIAL_SIZE (4)
int main(void)
{
char **list = (char **) malloc(INITIAL_SIZE * sizeof(char *));
int list_size = INITIAL_SIZE;
for (int i = 0; i < list_size; i++) {
list[i] = (char *) malloc(5 * sizeof(char));
strcpy(list[i], "jane");
}
printf("main--> address of list: %p\n", list);
/* output = 0x7fc15e402b90 */
addItems(list, &list_size);
/* After adding items: */
printf("main--> address of list: %p\n", list);
/* output = 0x7fc15e402b90 (no change) */
return 0;
}
Here are the other two example functions:
void doubleSize(char ***list, int *current_size)
{
char **newList = (char**) malloc(*current_size * 2 * sizeof(char*));
for (int i = 0; i < *current_size; i++)
newList[i] = (*list)[i];
free(*list);
*list = newList;
*current_size = (*current_size) * 2;
}
void addItems(char **list, int * size)
{
printf("Before doubling: %p\n", list);
/* Output: 0x7fc15e402b90 */
/* Double the size */
doubleSize(&list, size);
printf("After doubling: %p\n", list);
/* Output: 0x7fc15e402be0 */
}
The address of list
is getting changed to the newly created array inside doubleSize
and also inside addItems
but not inside the main function, even though we're passing a pointer to the array. What am I missing here?