waka-waka-waka
waka-waka-waka

Reputation: 1045

C struct return pointer, store in reference

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!

Upvotes: 0

Views: 635

Answers (4)

ArtemB
ArtemB

Reputation: 3632

&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.

Upvotes: 1

ajay
ajay

Reputation: 9680

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  

Upvotes: 1

user376507
user376507

Reputation: 2066

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.

Upvotes: 1

Kissiel
Kissiel

Reputation: 1955

&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).

Upvotes: 1

Related Questions