I'm getting the invalid lvalue error using gcc 3.4.6. The line that invokes the error has a function that receives a pointer to SetElement (which is typedef void*
). I'm trying to achieve this using casting from another type (also typedef void*
) the following way: &((SetElement)my_var)
. gcc complains about this. Any idea what can be done?
views:
874answers:
1
+2
A:
You are taking the address of a temporary (an rvalue
), which cannot be done. This is like trying to do:
&(2+2)
// or
&4
// or
&(my_ptr + 4)
You can create a temporary yourself (thus an lvalue
), using one of two methods:
AnotherType **my_var_ptr = &my_var;
SetElement **set_element_ptr = (SetElement *)my_var_ptr;
// or
SetElement *set_element = (SetElement)my_var;
SetElement **set_element_ptr = &set_element;
Or you can simply cast in a different way (solution):
SetElement **set_element_ptr = (SetElement *)&my_var;
This works because you're taking the address of my_var
(an lvalue
), and not of (SetElement)my_var
(an rvalue
).
strager
2009-01-02 20:39:42
Why is it a temporary address? And isn't there a way to do this directly?
CS student
2009-01-02 20:58:08
strager
2009-01-02 21:00:34
Also, I don't think there is a way to do this directly without a temporary. If you take the address of a temporary, the temporary will be destroyed and your pointer will be invalid (pointing to nothing useful; undefined).
strager
2009-01-02 21:01:23
Ah, I just had an epiphany. =] Yes, you can do it in one line. See my edit.
strager
2009-01-02 21:02:14
Since you've edited it, you may want to edit the paragraph that introduces it, too, since you have three, not two, and the student probably wants the first or second one.
Rob Kennedy
2009-01-02 21:08:57
@Kennedy, ah right, of course. =]
strager
2009-01-02 21:25:27