在函数的返回类型中定义结构

Jey*_*ram 4 c struct

#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;
}
Run Code Online (Sandbox Code Playgroud)

在上面的程序中,我试图定义一个提到返回类型的结构.struct s已成功定义.

这是有效用法吗?我从未见过像这样的真实场景.

如何让这个程序工作?

我收到此编译器错误:

asd.c: In function ‘main’:
asd.c:21:15: error: lvalue required as unary ‘&’ operand
Run Code Online (Sandbox Code Playgroud)

Ker*_* SB 7

除了你的memcpy行之外的所有东西都是正确的(尽管有点难以阅读),并且编译器错误告诉你什么是错的:你不能取"临时"的地址(即函数调用表达式的结果).

然而,你可以而且应该写出更自然的方式:

struct s ss = fun();
Run Code Online (Sandbox Code Playgroud)