I’m trying to learn C, and I’m hung up a bit on Pointers to Pointers. I think I understand why you need them, but can’t quite get my head wrapped around what is happening.
For instance, the following code doesn’t seem to work as I would expect it to:
#include <stdio.h>
int newp(char **p) {
char d = 'b';
*p = &d;
/*printf("**p = %c\n", **p);*/
return 1;
}
int main() {
char c = 'a';
char *p = &c;
int result;
result = newp(&p);
printf("result = %d\n", result);
printf("*p = %c\n", *p);
printf("c = %c\n", c);
return 0;
}
The result I get is this:
result = 1
*p =
c = a
*p prints as nothing. Instead, I would expect *p = b.
However, if I uncomment line 6 (the printf in the newp function), then I get this:
**p = b
result = 1
*p = b
c = a
What am I missing?
You are dealing with undefined behaviour. The variable
dis local (resides on the stack) and is not available after the enclosing function (newp) returns.When dereferencing
poutsidenewp, the address on the stack&dmay be overwritten by some other local variable or it may contain garbage.