Dollarslice
Dollarslice

Reputation: 10284

Why can't I take the address of a return value?

I've split some code into two files, it was working before. In one file I have a function which has an out value parameter which is a pointer to a pointer.

I'm filling this parameter with a call to a getter and dereferencing it:

foo(&bar());

however I get an error saying ''&' requires an l-value'. I understand what this error means, but I thought I would be able to do this because it's a pointer and so does represent the original 'thing'.

Is it something to do with the fact that the actual pointers memory location could change, even though it would point to the right thing? but why did it work before when it was in the same file and not now?

Thanks in advance!

Upvotes: 3

Views: 208

Answers (4)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215201

Assuming foo takes a pointer-to-int, try:

foo((int[]){bar()});

Upvotes: 1

Eran Zimmerman Gonen
Eran Zimmerman Gonen

Reputation: 4507

Using &, you aren't dereferencing, but referencing. To derefrence, use * instead: foo(*(bar()));.

And if you do want to reference it, put the result of bar() in a temporary variable:

x = bar();
foo(&x);

Upvotes: 2

Skizz
Skizz

Reputation: 71060

I guess bar() is:

type *bar () { return member_pointer; }

which returns the pointer member_pointer by value, hence not an l-vlaue.

If you want to modify the value member_pointer in foo(), you need:

type **bar () { return &member_pointer; }

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612894

Well, you need an lvalue, i.e. something that can be assigned to. You can't assign to the return value of a function.

You need to do something like this:

temp = bar();
foo(&temp);

Upvotes: 5

Related Questions