I need help with malloc()
inside another function.
I\'m passing a pointer and size to the fu
As mentioned in the other answers, we need a pointer to the pointer. But why?
We need to pass the value by a pointer in order to be able to modify the value. If you want to modify an int
, you need to pass it by the int*
.
In this question, the value we want to modify is a pointer int*
(pointer changed from NULL
to the address of the allocated memory), so we need to pass a pointer to the pointer int**
.
By doing followed, pInt
inside foo(int*)
is a copy of the argument. When we allocate memory to the local variable, the one in the main()
is intact.
void foo(int* pInt)
{
pInt = malloc(...);
}
int main()
{
int* pInt;
foo(pInt);
return 0;
}
So we need a pointer to pointer,
void foo(int** pInt)
{
*pInt = malloc(...);
}
int main()
{
int* pInt;
foo(&pInt);
return 0;
}