cpointersreallocpointer-to-pointer

Using realloc with pointer to pointer in another function


I'm trying to use realloc in this program to increase an array's size, using pointer to pointer. But it doesn't end up doing the task:

#include <stdio.h>

void push(int** data)
{
    *data = (int *)realloc(*data, 5 * sizeof(int));
    *data[4]=100;
}

int main() {
int *array = (int *)malloc(2 * sizeof(int));

push(&array);

printf("%d", array[4]);

free(array);
return 0;
}

I don't want to use a global variable as the array and I want the changes to be made to the array directly. What should I do?


Solution

  • This line doesn't do what you think:

    *data[4]=100;
    

    The array subscript operator has higher precedence than the unary dereference operator. So the above is the same as this:

    *(data[4])=100;
    

    Which is not what you want. You need parenthesis to first dereference the pointer then subscript the array.

     (*data)[4]=100;