I try it :
#include
#include
void foo(int* x)
{
x = (int *)malloc(sizeof(int));
*x = 5;
}
int main()
{
int a;
In foo
, variable x
is a local variable, a pointer to an int - it is a variable containing a value which is the address of an int
in memory.
You are calling the function with the address of main's a
variable. But then you are changing x
x = (int *)malloc(sizeof(int));
This changes x
to be a different value, the address of an area of memory now reserved for our use. HOWEVER, x
is a variable local to foo
. When foo
ends, x
goes away, and we return to main
. Two things have happened:
You then print out the contents of main
s a
. a
is still at the same location it was before we called foo.
Perhaps this previous answer to a related question will help you: Pointer errors in the method of transmission(c++)