【问题标题】:Can I return a struct a from a function that the struct is defined in? (c)我可以从定义结构的函数返回结构 a 吗? (C)
【发布时间】:2021-10-15 11:15:33
【问题描述】:

我试图在函数内部定义一个结构并在函数末尾返回该结构,但无法找出正确的方法来执行此操作。 例如:

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

【问题讨论】:

  • 不能那样工作。该结构需要在所有使用它的函数都可见的范围内定义。如果您尝试动态创建类型,C 不会这样做。
  • 您也不要在return 语句中输入类型名称,它必须是一个表达式。
  • 你可以 malloc 它并返回一个指向创建的结构的指针。如果你静态分配它,它会在函数调用的栈帧中结束,返回后无效。
  • 结构定义不是变量,它们是类型定义。您先定义一个结构,然后再声明该类型的变量。

标签: c function struct


【解决方案1】:

我可以从定义结构体的函数返回结构体 a 吗?

没有。

我正在尝试在函数中定义结构

不要那样做。先定义struct

struct Animals {
     int age;  // int makes more sense here than `int *`
     char* name;
};

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

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

小心管理.name 指向的成员。

【讨论】:

    猜你喜欢
    • 2021-10-18
    • 2012-09-20
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多