Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a pointer to struct returned from a function

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.

like image 531
Twifty Avatar asked Mar 03 '23 01:03

Twifty


1 Answers

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.

like image 75
Some programmer dude Avatar answered Mar 12 '23 23:03

Some programmer dude