-1
#include<stdio.h>
int main() {
int x = 5;
int* p = &x;
*p = 6;
int** q = &p;
int *** r= &q;
printf("%d\n",*p); //dereferencing p
printf("%d\n",*q); //getting address of q
printf("%d\n",**q); //dereferencing q
printf("%d\n",**r); //getting address of r
printf("%d\n",***r); //dereferencing r
}

Variable q has the memory address of p while variable r has the memory address of q, then why does when trying to print the memory address of q and r same results are getting produced?

Renz Carillo
  • 349
  • 2
  • 11
  • 4
    Nowhere here do you print the memory address of `r` (that would be `printf("%p\n", r);`). Also, the correct format specifier for pointers is `%p`, `%d` might even truncate the address. – mediocrevegetable1 Apr 18 '21 at 09:48
  • What do you mean by "memory address of q and r"? – MikeCAT Apr 18 '21 at 09:48
  • 3
    The inline comments are (a) wrong, and (b) don't match the description you typed in this question (which appears to be considerably more accurate). And unrelated, print addresses with `%p`, not `%d`. The second and fourth `printf` lines should both be using `%p`. – WhozCraig Apr 18 '21 at 09:49

1 Answers1

2

Your comments show that you have misunderstood a few things here.

printf("%d\n",*q); //getting address of q

You're NOT getting the address of q. You're dereferencing q, which happens to be the address of p. The * IS the dereferencing operator. If you want to print the address of q, then do this:

printf("%p\n", (void*)&q); // No asterisk and you should use the %p specifier for printing pointers.

So, because you have made the assignment p=&x; q=&p; then

  • **q is the same as x or *p
  • *q is the same as p
  • q is the the same as &p
  • &q is the address of q
klutt
  • 30,332
  • 17
  • 55
  • 95
  • `printf("%p\n", (void*)q);` print the address stored in `q`. `printf("%p\n", (void*)&q);` prints the address of `q`. – MikeCAT Apr 18 '21 at 09:51
  • Isn't the cast to `void *` a bit redundant since all pointers (except for function pointers) can implicitly convert to `void *` anyway? – mediocrevegetable1 Apr 18 '21 at 09:53
  • @mediocrevegetable1 This is not an implicit conversion. It has to do with that it's a variadic function. – klutt Apr 18 '21 at 09:57
  • @mediocrevegetable1: There is no implicit conversion of pointers passed to `printf`. Arguments passed for a `...` in a function declaration are subject to the default argument promotions. Those do things like converting `float` to `double`, but they do not convert pointers. – Eric Postpischil Apr 18 '21 at 09:59
  • @klutt I just looked it up and found [this question](https://stackoverflow.com/questions/24867814/printfp-and-casting-to-void), so you're right, sorry about that :p – mediocrevegetable1 Apr 18 '21 at 10:00
  • @mediocrevegetable1 No worries. Have made that mistake myself. It's easy to do. – klutt Apr 18 '21 at 10:00