Pointers to Pointers vs Normal Pointers in C – Key Differences

c++pointers

The purpose of a pointer is to save the address of a specific variable. Then the memory structure of following code should look like:

int a = 5;
int *b = &a;

…… memory address …… value
a … 0x000002 ………………. 5
b … 0x000010 ………………. 0x000002

Okay, fine. Then assume that now I want to save the address of pointer *b. Then we generally define a double pointer, **c, as

int a = 5;
int *b = &a;
int **c = &b;

Then the memory structure looks like:

…… memory address …… value
a … 0x000002 ………………. 5
b … 0x000010 ………………. 0x000002
c … 0x000020 ………………. 0x000010

So **c refers the address of *b.

Now my question is, why does this type of code,

int a = 5;
int *b = &a;
int *c = &b;

generate a warning?

If the purpose of pointer is just to save the memory address, I think there should be no hierarchy if the address we are going to save refers to a variable, a pointer, a double pointer, etc., so the below type of code should be valid.

int a = 5;
int *b = &a;
int *c = &b;
int *d = &c;
int *e = &d;
int *f = &e;

Best Answer

In

int a = 5;
int *b = &a;   
int *c = &b;

You get a warning because &b is of type int **, and you try to initialize a variable of type int *. There's no implicit conversions between those two types, leading to the warning.

To take the longer example you want to work, if we try to dereference f the compiler will give us an int, not a pointer that we can further dereference.

Also note that on many systems int and int* are not the same size (e.g. a pointer may be 64 bits long and an int 32 bits long). If you dereference f and get an int, you lose half the value, and then you can't even cast it to a valid pointer.