Home > Software design >  Is dereferencing a pointer an alias for the pointed variable or does it just access the value of the
Is dereferencing a pointer an alias for the pointed variable or does it just access the value of the

Time:04-06

I am not able to fully understand the nature of dereferencing operator. Does dereferencing is just an alias of the pointed variable or it fetches the value of the variable.

We know that for constant doing &constant is invalid as a constant does not have its own memory.
Now suppose we have something like this-


int i=5;

int *ptr=&i;

And then if we do &(*ptr) then how it will happen on lower level?

There are two three things in my mind let me take you to the all.

Case 1: I read that *ptr gives the value at that memory location so by this in mind &(*ptr) will evaluate to &5 but this will give an error as 5 is a constant.

Case 2: That *ptr is just an alias for the variable 'i' then &(*ptr) will become &i and this looks fine by me.

Case 3: What I was told that & and * cancels each other out in the expression &(*ptr) but I am not able to get it. How they cancels each other out?

CodePudding user response:

In the C standard :

A.7.4.3 Indirection Operator The unary * operator denotes indirection, and returns the object or function to which its operand points. It is an lvalue if the operand is a pointer to an object of arithmetic, structure, union, or pointer type. If the type of the expression is ``pointer to T,'' the type of the result is T.

So, *ptr will return an lvalue and not the value stored in i (So, saying it returns an alias is right). The & operator can be used on this lvalue and you get the same result as &i on using &(*ptr).

So, it is case 2

And, for saying that & and * cancel each other out, as we see above, &(*ptr) will evaluate to the same result as &i which is the same as just ptr. So, in the end result, you can say, they cancelled each other. But, unless the compiler decides to do some optimizations and remove the & and *, first the *ptr gets evaluated and then the & operates on that result.

CodePudding user response:

It literally does the 2nd case. As a pointer points to a local stack variable the &(*ptr) will get it's address.

The constant variables do have their memory in the same way as non-constants. But if it doesn't manipulate their memory address in any way, the optimizer may carve it out and put constant values just-in-place.

  • Related