Twi*_*fty 4 c struct casting function return-value
我有一个函数,它克隆一个结构体的成员并返回一个结构体(不是指针)。这个新创建的对象是短暂的。
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;
}
Run Code Online (Sandbox Code Playgroud)
我不能返回一个指针,因为它会指向已释放的内存。如何将克隆函数的返回值作为指向第二个函数的指针传递?类似于以下内容,但不使用中间占位符。
void do_sth(struct my_struct const *p);
struct my_struct val = my_struct_clone(&other, 123);
do_sth(&val);
Run Code Online (Sandbox Code Playgroud)
以下失败(左值需要作为一元“&”操作数):
do_sth(&(my_struct_clone(&other, 123)));
Run Code Online (Sandbox Code Playgroud)
但是可以声明一个 struct inline
do_sth(&(struct my_struct){.a = 1, .b = 2});
Run Code Online (Sandbox Code Playgroud)
解决一些关于使用中间体的评论。问题是关于避免创建一个,而不是“我不能使用一个,因为......”。我最近遇到了一个编码结构,我认为我可以,但发现我不能,因此提出了这个问题。此外,将已经分配的实例传递给 clone 函数仍然需要一个中间件。我宁愿不要用像这样短暂的变量声明来混淆函数头。