Is the only way of getting the address of an address in C (opposite to double dereference to have an intermediate variable?
e.g. I have:
int a;
int b;
int *ptr_a;
int *ptr_b;
int **ptr_ptr_a;
a = 1;
ptr_a = &a;
ptr_ptr_a = &(&a); <- compiler says no
ptr_ptr_a = &&a; <- still compiler says no
ptr__ptr_a = &ptr_a; <- ok but needs intermediate variable
but you can do the inverse, e.g.
b = **ptr_ptr_a; <- no intermediate variable required
e.g. I don't have to do:
ptr_b = *ptr_ptr_b;
b = *ptr_b;
why are the two operators not symmetrical in their functionality?
It is probably easier to explain with an example memory layout like this:
Var Adr value
---------------------
a 1000 1
ptr_a 1004 1000
ptr_ptr_a 1008 1004
1008 1004 1008->1004->1000
You can obviously dereference ptr_ptr_a twice *ptr_ptr == ptr_a, **ptr_ptr_a == 1
But the variable a
has an address (1000) what should address of an address mean if it is not the address of a pointer? &a
is a final station. Thus &&a
wouldn't make any sense.
The address-of operator returns an rvalue, and you cannot take the address of an rvalue (see here for an explanation of the differences between rvalues and lvalues).
Therefore, you have to convert it into an lvalue by storing it in a variable, then you can take the address of that variable.
address of address of something is not possible, because an address of address would be ambiguous
You can get the address of something which hold the address of something, and you could have multiple occurances of that (with different values)
When you ask for an address using '&', you ask the address for something stored in memory. Using '&' 2 times means you want to get the address of an address which is non-sense.
By the way, if you use intermediate variable as you're doing it, you will get the address of the intermediate variable. Which means if you use 2 intermediate variable to compare addresses they will be different. eg.:
int a = 0;
int* p = &a;
int* q = &a;
// for now &p and &q are different
if (&p == &q)
printf("Anormal situation");
else
print("Ok");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With