c - 结构的存储大小未知

标签 c

我希望我的结构位于 main() 函数作用域中。 当我这样做并使用 typedef 时,出现错误:存储大小...未知

typedef struct client client;

int main()
{


    struct client {
        int var;
        char c;
    };


    client person1;

    return 0;
}

我这样做是为了摆脱 struct 关键字。
为什么会出现此错误?如何在我的 main() 函数中创建结构来成功完成此错误?

最佳答案

您收到的错误是因为您实际上有两种在不同范围声明的名为 struct client 的类型。

typedef 在文件范围内声明一个struct client,并为其指定别名client。然后,当您在 main 函数内定义 struct client 时,它会在文件范围内屏蔽。然后,当您尝试声明 client 类型的变量时,它会在文件范围内引用从未定义的 struct client

要解决此问题,typedef 和结构定义需要位于同一范围内。因此,您可以将它们都放在 main 中:

int main()
{
    typedef struct client client;
 
    struct client {
        int var;
        char c;
    };

    client person1;

    return 0;
}

或者两者都在文件范围内:

typedef struct client client;

struct client {
    int var;
    char c;
};

int main()
{
    client person1;

    return 0;
}

关于c - 结构的存储大小未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65253375/

相关文章:

c - C 结构体数组排序函数

c - 相互排斥并不排斥

c - 为什么可以在不同的文件中使用与其原型(prototype)不同数量的参数重新定义函数?

android - JNIEnv 用于从 native 代码获取 ANDROID_ID

c - 无法使用 'strcpy()'函数。即使使用 #include <string.h> 后也会生成错误

c - 如何将指针赋值给全局变量?

c - 日历中的 PE(显示错误)

c++ - 无法让 Makefile 工作

c - 如何减少 NCurses C 应用程序中的输入延迟

c - 如何在c中切换数字的替代位