Reputation: 425
How does the * operator work in this example, and why does it work?
int *p, x, y;
x = 5;
p = &x; // stores the address of x in p;
y = *p; // the * operator gets the value stored at the address stored in p. Now y is 5;
*p = 0; // why does this work? Shouldn't it be as writing 5 = 0? since the * operator gets the value stored at that address?
Why does *p = 0 assigns 0 to x? I've commented the code to better understand what I'm missing here.
Thank you!
Upvotes: 0
Views: 83
Reputation: 170299
When you write *p
it doesn't just mean "fetch the value at the location pointed by p
". It's an expression, and expressions in C have one of two value categories. They are informally lvalues and rvalues. Roughly speaking, the L and R indicate on which side of an assignment can the expression appear. An lvalue may appear on the left (and "be assigned to"), while an rvalue may not.
For instance, if you have this (condensed for brevity) piece of code:
struct point { int x; int y;};
struct point p;
p.x = p.y = 1;
Then p.x
and p.y
are each an lvalue expression. And so can be assigned to. In the same way, pointer indirection gives us an lvalue as well. We can even see it says as much in the C language standard:
6.5.3.2 Address and indirection operators - p4
The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ''pointer to type'', the result has type ''type''. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.
Upvotes: 8
Reputation: 463
since pointers store the address of the variable.. so in your code *P has an address of x... say suppose address of x =23, address of y=24 since p is pointer then address of p is equivalent to address of x which is 23
x=5;// stores 5 in the address 23
p =&x //it has an address of x which is 23
y= *p // so gets the value 5 as you told
*p = 0// now stores the value 0 in the address 23. as x is having address 23 automatically x value changes to zero
Upvotes: 0