[英]defining structure in return type of a function
#include <stdio.h>
#include <string.h>
struct s
{
int data;
} fun()
{
static struct s ss;
ss.data = 20;
return ss;
}
int main()
{
struct s ss;
memcpy(&ss, &(fun()), sizeof(struct s));
printf("\n Data: :%d", ss.data);
return 0;
}
In the above program, Im trying to define a struct where the return type is mentioned. 在上面的程序中,我试图定义一个提到返回类型的结构。
struct s
is defined successfully. struct s
已成功定义。
Is this a valid usage? 这是有效用法吗? I never seen real scenario like this.
我从未见过像这样的真实场景。
How to make this program to work?? 如何让这个程序工作?
I'm getting this compiler error: 我收到此编译器错误:
asd.c: In function ‘main’:
asd.c:21:15: error: lvalue required as unary ‘&’ operand
Everything apart from your memcpy
line is correct (albeit a bit hard to read), and the compiler error tells you what's wrong: You can't take the address of a "temporary" (ie of the result of a function call expression). 除
memcpy
行之外的所有内容都是正确的(尽管有点难以阅读),并且编译器错误告诉您错误:您不能获取“临时”的地址(即函数调用表达式的结果)。
You could and should however just write the much more natural way: 然而,你可以而且应该写出更自然的方式:
struct s ss = fun();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.