【问题标题】:C Struct : typedef Doubt !C 结构:typedef 怀疑!
【发布时间】:2011-01-15 15:35:49
【问题描述】:

在给定的代码 sn-p 中,我预计会出现错误 symbol Record not found。但它在 Visual Studio 2010 编译器上编译并运行良好。我以 C 程序从 Visual Studio 2010 命令提示符中运行它 -

cl Record.c
记录

现在的疑问是,typedef 不检查符号吗?它更像forward declaration 吗?

#include "stdio.h"
#include "conio.h"

typedef struct Record R;
struct Record
{
    int a;
};

int main()
{   
    R obj = {10};
    getch();
    return 0;
}

【问题讨论】:

  • 试着把typedef struct Record R;放在struct Record ...下面
  • @xhan - 如果我这样做,它是有意义的,因为符号 Record 更早被发现。谢谢。
  • 您的代码在 GCC(必须将 getch 更改为 getchar)和 VS2005 下运行良好。我怀疑你的发现是正确的。

标签: c struct typedef


【解决方案1】:

您始终可以引用未定义的结构,毕竟这是实现链表的典型方式。当您想使用它们的字段时,只需定义它们。 This page 包含一些细节。

【讨论】:

    【解决方案2】:

    C 找不到符号 Record,因为它是稍后在代码中声明的,就像您尝试使用您在代码中声明过去但未定义其原型的函数一样。

    你也可以把这两个声明结合起来,然后就变成了:

    typedef struct Record
    {
        int a;
    } R;
    

    它也有效,而且在我看来甚至更好,不是因为它可以更快,而是因为它更小。

    【讨论】:

    • 较小的是 typedef struct { int a; } R;
    【解决方案3】:

    typedef 必须在其第一个参数定义后使用。

    struct Record
    {
        int a;
    };
    typedef struct Record R;
    

    typedef struct Record
    {
        int a;
    } R;
    

    如果您需要在结构中使用struct Record,只需使用struct Record

    typedef struct Record
    {
        struct Record *next;
    }
    typedef struct Record R;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多