I need help with malloc()
inside another function.
I\'m passing a pointer and size to the fu
Parameters' assignment will work only if you set the value to its address.
There are 2 points that you should know before you attempt to solve this problem:
1. C Function: All the parameters you passed to the function will be a copy in the function.
That means every assignment that you've made in the function will not affect the variables outside the function, you're working on the copy actually:
int i = 1;
fun(i);
printf("%d\n", i);
//no matter what kind of changes you've made to i in fun, i's value will be 1
So, if you want to change i in the function, you need to know the difference between the thing and its copy:
The copy shared the value with the thing, but not the address.
And that's their only difference.
So the only way to change i in the function is using the address of i.
For example, there's a new function fun_addr:
void fun_addr(int *i) {
*i = some_value;
}
In this way, you could change i's value.
The key point in the fun_addr function is, you've passed a address to the function. And you could change the value stored in that address.
What will malloc do?
malloc will allocate a new memory space, and return the pointer pointed to that address back.
Look at this instruction:
int *array = (int*) malloc(sizeof(int) * SIZE);
What you are doing is let array's value equals to the address returned by malloc.
See? This is the same question, permanently assigning value to the parameter passed to the function. At this point, the value is address
.
Now, assign the address(returned by malloc) to the address(stores the old address).
So the code should be:
void fun_addr_addr(int **p) {
*p = (int*) malloc(sizeof(int) * SIZE);
}
This one will work.