439 views
1 votes
1 votes

For the structure variable x , what is the difference between  x and &x ?

Also why is &x.val is an error ? Isn't it the address of the structure to which x is pointing to ?

struct node
{
int val;
struct node * next;
}x;
int main()
{
x.val=3;
&x.val=4;
return 0;

}

 

2 Answers

3 votes
3 votes

basic points :-

int i; ---- i is the variable of data type of int

int *p; ---- p is the variable of data type of int *


in your question

x is the variable of data type of node

&x is the address of the variable of data type of node

 

x.val=3 ===> x is a structure variable ===> x.val is a member of x  and it's data type is int===> x.val = 5

 

&x.val=4 ===> By precedence rules (& (x.val) ) = 4 ==> you are using the address of variable x.val as l-value

all we know that, memory addresses can't use as l-value, therefore above statement generates compilation error

2 votes
2 votes
When you have an assignment operator in a statement, the LHS of the operator must be something the language calls a $\textit{lvalue}$. If the LHS of the operator does not evaluate to a $\textit{lvalue}$, the value from the RHS cannot be assigned to the LHS.

For eg. you cannot use 10 = 20 as on the LHS of the equation is not a lvalue.

& operator is a unary operator which is used to get the address of an operand. It is okay to define a new pointer and make the pointer store the address returned by the &x.val but you cannot write anything to &x.val (There is nothing to write to).

Eg.

int *ptr;
ptr = &x.val;

x.val will simply be the val field of struct x. Which is a location and hence one can store data in it. Hence, it is legal to use it in LHS in assignment operator.
edited by

Related questions

0 votes
0 votes
1 answer
2
radha gogia asked Jul 21, 2015
339 views
char ch;scanf("%c",&ch) // after I do scanning of this variable then after I press enter key then it gets stored inside the buffer so can we print this enter key .Since d...
1 votes
1 votes
3 answers
3
jverma asked May 23, 2022
1,090 views
#include <stdio.h>int f(int n){ static int r = 0; if (n <= 0) return 1; r=n; return f(n-1) + r;}int main() { printf("output is %d", f(5)); return 0;}Ou...