To change the original pointer p
declared within the function main
in function allocate
you need to pass it by reference. Otherwise the function will deal with a copy of the value of the original pointer p
and changing the copy will not influence on the value stored in the original pointer.
In C passing by reference means passing an object indirectly through a pointer to it. So dereferencing the pointer you will get an access to the original object.
Consider the following demonstrative program.
#include <stdio.h>
void f( int x )
{
x = 20;
}
int main(void)
{
int x = 10;
printf( "Before calling the function d c = %d\n", x );
f( x );
printf( "After calling the function d c = %d\n", x );
return 0;
}
Its output is
Before calling the function d c = 10
After calling the function d c = 10
As you can see the original variable x
was not changed after calling the function f because the variable is passed by value to the function.
Now consider the following program.
#include <stdio.h>
void f( int *px )
{
*px = 20;
}
int main(void)
{
int x = 10;
printf( "Before calling the function d c = %d\n", x );
f( &x );
printf( "After calling the function d c = %d\n", x );
return 0;
}
At this time the program output is
Before calling the function d c = 10
After calling the function d c = 20
As the variable x
was passed by reference then dereferencing the pointer
px
*px = 20;
you get a direct access to the original variable x
through the pointer.
So if you want to change a pointer itself then passing it by reference means passing a pointer to the pointer the same way as it was done in the function above only now the type of the original variable p
is int *
instead of int
.
That is if you have a declaration like this
T x;
where T
is some type (as for example int
or int *
) then to pass the variable by reference you need to use a function argument expression like &x
. that will have the type T *
. If T
is equivalent to the type int *
then you need to use an argument expression of the type int **
.