0

I have a simple question which I am trying to figure out why...

I have a function that returns a struct pointer. And I have a struct variable 'a'.

&a = somefunc(...) // returns a pointer to my struct.
error: lvalue required as left operand of assignment

Why does the above not work, while the following works...

struct whatever *b = somefunc(...)

My thinking is, in both cases, I am returning something of type struct whatever.

Thanks!

4 Answers 4

1

The address of operator & yields an rvalue which is the memory address of its operand. You can't have an rvalue on the left side of an assignment. Hence you need an lvalue and to store the address of a variable, you need a pointer type variable.

struct mystruct {
    int marks;
    char grade;
};

// a is of type struct mystruct. 
// stores a value of this type

struct mystruct a; 

// b is pointer to struct mystruct type.
// stores the address of a variable of this type.

struct mystruct *b;

b = &a; // assign b the address of a  
Sign up to request clarification or add additional context in comments.

Comments

1

&a means "give me address of a", which is not a l-value (you cannot assign anything to it). In second example *b is a valid l-value

You can think of &a returning 100. You cannot do 100 = something. While b is a valid variable (of type pointer).

Comments

1

Only a pointer can hold addresses, you are trying to assign an address to an address i.e. a value to a value in the first case.

Comments

1

&a means address of a. You can't assign anything to an address of something. Think of it as your email address in general -- people can ask you for it and they can use it after you gave it to them, but they can't change it.

On the other hand, *b is a variable that contains an address of struct whatever. That's something that you can store a value in. In email terms that would be a whiteboard with dedicated space where you write your email address. If someone wants to change it, they can do it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.