Reputation: 13
While I was reading C++ Primer, found this example that i don't understand
double dval;
double *pd = &dval; //ok:initializer is the address of a double
double *pd2 = pd; // ok:initializer is a pointer to double
Shouldn't *pd2
be a pointer to pointer since *pd
is a pointer aswell? Could somebody explain what happens in the background with the memory addresses( what is assigned to pd2
)?
Upvotes: 0
Views: 59
Reputation: 3288
A pointer is a memory address. double *pd2 = pd;
assigns one pointer to another pointer. No magic, just a simple assignment operation. Both pointers are pointing at the same memory address.
The value in pd2
is the same value as in pd
. if you were to dereference either pd
or pd2
you would get the value stored in dval
.
Assigning &pd
would require a pointer to a pointer since you are taking the address of a pointer.
Upvotes: 1
Reputation: 547
First you declare a double dval
, then you declare a pointer, that points on that double (because its set by the doubles adress &dval
).
Then the second pointer is set equal to the first pointer.
So finally, you have:
pd = pd2 = &dval
Which are two pointers, pointing to the same adress, not a pointer pointing to another pointer.
Upvotes: 0
Reputation: 596121
Shouldn't
*pd2
be a pointer to pointer since*pd
is a pointer aswell?
No. pd2
is being assigned the value that pd
is currently holding. Thus pd2
ends up pointing at dval
. You would only use a pointer-to-pointer if you want pd2
to point at pd
itself, not what pd
is pointing at, eg:
double dval;
double *pd = &dval;
double **pd2 = &pd;
Could somebody explain what happens in the background with the memory addresses( what is assigned to pd2)?
A pointer is just a number that happens to be a memory address. If you think of pointers as integers, the code you provided is not much different than the following behind the scenes:
double dval;
uintptr_t pd = address of dval;
uintptr_t pd2 = pd;
You are just assigning one pointer value (a number) as-is to another pointer (number) variable.
Upvotes: 1
Reputation: 3125
The value of pd2
is what is assigned to it, that is the address of dval
, which was stored as value of pd
and assigned to the former.
Upvotes: 1