Your code contains two pointers: one in the create_int
function and another one in main
. When you call create_int
, a copy of the pointer in main
is made and used, then eliminated when the create_int
function returns.
So, any changes you did to the copy within create_int
remain there and are not propagated back to main
.
The only way to propagate changes between functions in C (aside from, obviously, returning new values) is to pass a pointer to the changed values. This way, while the pointer being passed will be copied, the value that it points to will be the same, so changes will apply.
Since you're trying to change a pointer, you need a pointer-to-pointer.
void create_int(int **pp)
{
// this changes the pointer that `p` points to.
*pp = (int *) malloc(sizeof(int));
}
int main()
{
int *p = NULL;
// this sends a pointer to the pointer p in main
create_int(&p);
assert(p != NULL);
return 0;
}