Remember that when you pass parameters to functions, you're actually passing a COPY of the variable and not the variable itself. This applies just the same to pointers.
f0
Note that this creates a
copy of the passed pointer. Even though you pass p0 to the function, 'p' is a seperate variable. So when you change 'p' with that malloc line, p0 remains unchanged (still NULL)
Also, once you return from this function, you have a memory leak because you cannot free() what you malloc here.
f1
This is a great exaimple why C's lack of type safety can be troublesome.
Here your pointer 'p' points to 'p1'. But then when you malloc, you change 'p' to point to newly allocated space instead (so it will no longer point to p1)
Notice that you're modifying the local pointer 'p' and not the pointer that 'p' points to. Therefore p1 remains unchanged.
The correct way to do this would be like so:
1 2 3 4 5
|
void f1(char **p) {
*p = malloc(100); // change the pointer that p points to
printf("Pointer in f1: %p\n", *p); // print that pointer
return;
}
|
You can think of it this way.... because p points to p1, *p
is p1. Therefore changes to *p (read: not p) will change p1.