1

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?

1
  • In your question, you wrote: "But it doesn't end up doing the task" -- This is not a sufficient description of the problem. In what way does the program not work? Do you maybe get an error message from the compiler? If so, then you should state this in your question and post the error message that you are getting. Commented Dec 24, 2023 at 22:44

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

Comments

2

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.