Home > Blockchain >  dereferencing pointer to a pointer with one Asterisk [duplicate]
dereferencing pointer to a pointer with one Asterisk [duplicate]

Time:10-08

#include <stdio.h>
int main(){
    int integer = 300;
    int* p = &integer;
    int** pp = &p;
    printf("*pp = %i", *pp);
}

My question is what is actually *pp? What does it mean to print the value in the address of *p ?

CodePudding user response:

It is a reference to the integer converted to an integer value.

To print the reference you should use %p format specifier instead of the %i format specifier.

[pp] -> [p] -> [integer]

If you modify the program you can see the references and how they are chained:

int main()
{
    int integer = 300;
    int* p = &integer;
    int** pp = &p;
    printf("pp = %p *pp = %p\n",(void *)pp, (void *)*pp);
    printf("&integer = %p &p = %p\n", (void *)&integer, (void *)&p);
}
pp =        0x7fffb6adc7d8 *pp =    0x7fffb6adc7e4
&integer =  0x7fffb6adc7e4 &p =     0x7fffb6adc7d8

CodePudding user response:

#include <stdio.h>
int main(){
    int integer = 300;
    int* p = &integer;
    int** pp = &p;
    printf("**pp=%d\n", **pp);
    printf("*p=%d\n", *p);
    printf("*pp = %p\n", *pp);
    printf("p=%p\n", p);
    printf("&integer=%p\n", &integer);
    printf("&(*p)=%p\n", &(*p));
    printf("pp=%p\n", pp);
    printf("&p=%p\n", &p);
}

Since &(*p) is simply p, yes *pp is the address of *p.
Since %i is integer but what you want to print is pointer. So I changed it to %p.

CodePudding user response:

I'm not a pro in C programming, but I believe I have a decent knowledge of pointers. So, to understand what is *pp, you need to understand what is * operator used for?

It is no doubt used for multiplication, but it is also used for pointer de-referencing.

So when I say *pp, it means the value of pp i.e. what is stored in pp. Each defined variable in C will have a memory space of its own. So *pp means what is stored in the memory space that was given to the variable pp.

In your case,

int integer = 300;

A variable of type integer named integer is declared and given the value 300

int* p = &integer;

A pointer that needs to point to an integer variable is declared and given the address of integer.

int** pp = &p;

A pointer that needs to point to an integer variable is declared and given the address of p

printf("*pp = %i", *pp);

*pp means printing the value which is stored in pp i.e. address of p **pp means printing the value which is stored in the value which is stored in p i.e. 300

As I explained earlier, each variable has a memory space of its own, and each memory space will have an address assigned to it, so that it can be identified (the way we have an email address which is used to contact us via email or a postal address which is used to contact us via post).

Hope this answers your question. Do ask follow-up questions if any. Cheers..!!

  • Related