Lisha GuPta
Lisha GuPta

Reputation: 11

What does *(&a)=5 mean?

I’m studying about pointers. It’s quite confusing—maybe because I’m new. I have a question that what *(&a) indicates in the following short program.

On line 7, I know *(&a) means “value at address of variable a,” but on line 13, what does *(&a)=5 mean? When I assign &a=5, the compiler gives an error along the lines of “lvalue required as left operand of assignment,” but when I assign the value in *(&a), then it compiles with no error.

#include <stdio.h>

int main()
{
  int *p, a = 2, b;

  b = *(&a);         // line 7
  printf("%d", b);

  p = &a;
  printf("%d", p);

  *(&a) = 5;         // line 13
  printf("%d", a);

  return 0;
}

Upvotes: 0

Views: 933

Answers (3)

csnate
csnate

Reputation: 1641

&a will return a pointer to a, or the memory address where a is located. The dereference operator * returns the value of the data pointed to by the address. Consider the following code.

int foo = 3;
int* bar = &foo; /// bar points to foo.
printf( "%d\n", *bar ); /// will print 3
printf( "%d\n", *(&foo) ); /// will also print 3

The variable bar points to the memory address where foo is located. By using the dereference operator, you get the value stored in memory at the address contained in bar. The last example combines the two, you get a pointer to foo and immediately dereference it, which returns the value stored in foo

Upvotes: 0

user3920237
user3920237

Reputation:

This is covered in § 5.3.1 [expr.unary.op]:

1 The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points. If the type of the expression is “pointer to T,” the type of the result is “T.”

and:

2 The result of each of the following unary operators is a prvalue.

3 The result of the unary & operator is a pointer to its operand.

Since &a yields a prvalue, &a = 5 is invalid, because &a is not an lvalue. Only modifiable lvalues can appear on the left hand of the built-in assignment operator.

On the other hand, *(&a) yields an lvalue (making it assignable).

Upvotes: 0

nwp
nwp

Reputation: 9991

Given an int a; then &a gives you the address of a which is an int *. Given an int *p; the expression *p gives you the int that p is pointing to. So *(&a) is the value behind the address of a which is a. In other words *(&a) does the same as just a.

There are times when this is sort of useful. Given a std::vector<int>::iterator it; you can get a pointer to the int the iterator points to by dereferencing the iterator to get the int and then take the address, so you get &(*it).

Upvotes: 1

Related Questions