1

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 *?

Ardent Coder
  • 3,499
  • 9
  • 25
  • 46
G0rdo1
  • 63
  • 1
  • 6
  • Does this answer your question? [How do pointer to pointers work in C?](https://stackoverflow.com/questions/897366/how-do-pointer-to-pointers-work-in-c) – Gerhard Mar 25 '20 at 09:19

1 Answers1

5

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.

Some programmer dude
  • 380,411
  • 33
  • 383
  • 585