I have a function which clones members of a struct and returns a struct (NOT pointer). This newly created object is short lived.
struct my_struct {
int a;
int b;
};
inline struct my_struct my_struct_clone(struct my_struct src, int members){
struct my_struct copy = {0};
//... Do copy based on args
return copy;
}
I cannot return a pointer as it would be pointing to deallocated memory. How can I pass the return value of the clone function as a pointer to a second function? Similar to the following, but without using an intermediate placeholder.
void do_sth(struct my_struct const *p);
struct my_struct val = my_struct_clone(&other, 123);
do_sth(&val);
The following fails (lvalue required as unary ‘&’ operand):
do_sth(&(my_struct_clone(&other, 123)));
But it is possible to declare a struct inline
do_sth(&(struct my_struct){.a = 1, .b = 2});
To address some of the comments about using an intermediate. The question is about avoiding the creation of one, and not "I can't use one because...". I recently encountered a coding construct where I thought I could but discovered I couldn't, hence the question. Also, passing in an already allocated instance to the clone function still requires an intermediate. I would prefer to not clutter the function header with variable declarations that are short lived like this.
The value returned by the function is an rvalue, which means that its address can't be taken.
But compound literals are lvalues which means their address can be taken.
You need the temporary variable to be able to pass the result of the cloning function as a pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With