【问题标题】:typedef struct clarificationtypedef 结构说明
【发布时间】:2016-12-05 13:23:58
【问题描述】:

谁能解释一下这之间有什么区别:

typedef struct{
 char a[10];
 int b;
 char c[8];
 ...
}test;

还有这个:

typedef struct test{
 char a[10];
 int b;
 char c[8];
 ...
}test;

谢谢

【问题讨论】:

标签: c struct typedef


【解决方案1】:
typedef struct{
 char a[10];
 int b;
 char c[8];
 ...
}test;

上面定义了一个匿名结构,并立即将其typedefs 转换为类型别名test

typedef struct test{
 char a[10];
 int b;
 char c[8];
 ...
}test;

然而,这会创建一个名为 struct test 的结构,并为其添加一个 typedef

在第一种情况下,如果需要,您将无法转发声明 struct
还有一个philosophy(我恰好同意这一点),默认情况下typedefing 所有结构会使代码的可读性降低,应该避免。

【讨论】:

    【解决方案2】:

    在两个不同的地方进行“测试”有点令人困惑。我通常这样写代码:

    typedef struct test_s {
        ...
    } test;
    

    现在我可以使用类型struct test_s 或只使用test。虽然单独使用 test 通常就足够了(在这种情况下您不需要 test_s),但您不能前向声明指向它的指针:

    // test *pointer; // this won't work
    struct test_s *pointer; // works fine
    
    typedef struct test_s {
        ...
    } test;
    

    【讨论】:

    • _t 结尾的名称由标准保留。您可能只想使用typedef struct test_s { ... } test_s;。我认为 typedefed 名称与 struct 标记不同没有多大价值。
    • 很高兴知道。以后不再使用_t。区别只是为了清楚。
    【解决方案3】:

    第一个版本只能声明:

    test t;
    

    使用第二个版本,您可以选择:

    struct test t;
    test t;
    

    【讨论】:

      【解决方案4】:

      简答:它们是相同的(在您的代码中)

      长答案: 为什么要把test 放在typedef struct{ 之间?这没有意义吗?

      这(结构名称test)在您的代码中毫无意义

      然而,在这段代码中,它不是:

      struct Node {
        int data;
        struct Node * next;
      } head;
      

      【讨论】:

      • 存在差异,后者无效。
      • @Olaf 哦,我的错,我错过了struct
      • 他们还是不一样!
      • @Olaf 他们都在制作同一个结构,不是吗?
      • “make”是什么意思?该标准不使用该术语。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 2023-03-11
      • 2021-05-06
      • 1970-01-01
      相关资源
      最近更新 更多