I had to print the value of a pointer:
int *p = 0;
printf("%d", *p);
The code above throws an exception.
So I tried printf("%d", p)
and that worked.
Why did it work only without the *
?
I had to print the value of a pointer:
int *p = 0;
printf("%d", *p);
The code above throws an exception.
So I tried printf("%d", p)
and that worked.
Why did it work only without the *
?
When you derefererence the pointer p
(as *p
) you dereference a null pointer (you try to get the value where p
is pointing, but it's not actually pointing anywhere). This leads to undefined behavior and very often a crash.
When you use plain p
you print the contents of the pointer variable itself, not the value of where it's pointing. But that also leads to undefined behavior, because the %d
format is to print an int
value, not a int *
value. Mismatching format specifier and argument type is UB.