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
)?
pd2
的值是分配给它的值,即dval
的地址,该地址存储为pd
值并分配给前者。
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.
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.