Home > OS >  Pointer to pointer value not printing
Pointer to pointer value not printing

Time:02-02

I am new to C programming and recently covered pointers. I wrote some code which made me confused. I tried to make up a possible explanation but it didnt seem correct.

Here is my code:

#include <stdio.h>

int main() {
    int x = 5;
    int* p = &x;
    int*** q = &p; 
    printf("%u\n", *p);
    printf("%u\n", *q);
    printf("%u", ***q);
    return 0;
}

What I have done is that I have declared a pointer p to x and then a pointer q to pointer p itself. The video that I was watching, there was firstly a **q pointing to p and when I tried to dereference it, I got the value which I was able to understand why and how it was doing that.

Now, I thought to change **q to ***q and when I tried to dereference it, it printed:

5
// the address
// and then a new line

Can you tell me why this happened? And what is meant by adding more stars to a pointer?

CodePudding user response:

The general rule is a pointer to int with n-1 * should be with n * (or every other type), and the pointer points to int with n-1 stars

for example, let's look at int, n = 1 so a pointer to it should be with 1 *, so you have a pointer that if you dereference it you will get an int type.

so in your example, we have an int* so a pointer to it should be int**. here you have a pointer that if you dereference it you will get an int* type.

EDIT: add more explanation why you get an empty line.

note that *z simply tells the compiler to take the value in z and act on it as an address, so if the value in z is 1000, it's just looking at address 1000 and see what's in there. in your example, the compiler warns you that something is wrong, but if you want to do so, then go on.

as we explained, when you do *q you get p, when you do **q you get x, so when you do ***q you get the value of the address 5, it's the same as *5.

so the value in address 5 is not known, in the good case we may get a segmentation fault, but we can get anything, but the behaviour is defined your example.

we can look on the generated assembly(compiled with -O2, only ***q printing and removed some not interesting lines)

main:
.LFB11:
        movl    $.LC0,            
  •  Tags:  
  • Related