我可以从定义了该结构的函数中返回一个结构吗?(C)

时间:2021-08-12 03:55:29

标签: c function struct

我正在尝试在函数内定义一个结构体,并在函数末尾返回该结构体,但无法找到正确的方式。例如:

struct Animals test() {
    struct Animals {
         int* age;
         char* name;
    }
    return struct Animals;
}

1 个答案:

答案 0 :(得分:0)

可以从定义了结构体的函数中返回一个结构体吗?

不行。

我正在尝试在函数内部定义一个结构体。

不要这样做。先定义 struct

struct Animals {
     int age; // int 比 "int *" 更有意义
     char* name;
};

然后返回该 struct。对象的 可以在 test() 中定义,但对象的 结构 应该在 test() 之前和外部定义。

struct Animals test(void) {
    //     v------ compound literal  -----------------v
    return (struct Animals){.age = 42, .name = "fred" };
}

注意管理 .name 指向的成员。