Using realloc with pointer to pointer in another function

66 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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;
0
On

The problem is with operator precedence. You need

(*data)[4] = 100;

for your program to assign 100 to the fifth int in the newly allocated memory.

As you can see in the operator precedence table, [] comes before * (dereferencing).