Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C address of an address of a variable

Tags:

c

pointers

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?

like image 560
bph Avatar asked Apr 02 '12 12:04

bph


4 Answers

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? &ais a final station. Thus &&a wouldn't make any sense.

like image 71
stacker Avatar answered Oct 08 '22 20:10

stacker


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.

like image 36
Frédéric Hamidi Avatar answered Oct 08 '22 21:10

Frédéric Hamidi


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)

like image 27
stefan bachert Avatar answered Oct 08 '22 21:10

stefan bachert


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");
like image 39
delannoyk Avatar answered Oct 08 '22 19:10

delannoyk