【问题标题】:typedef is used on same struct twicetypedef 在同一个结构上使用了两次
【发布时间】:2014-11-23 16:15:06
【问题描述】:

我试图了解一段代码中的结构用法。这让我很困惑。看起来 typedef 在同一个结构上使用了两次。请谁能帮我理解为什么这段代码有两次typedef。有什么办法可以简化这段代码。 非常感谢您的时间。

typedef struct {
city_t* cities; 
int count;      
cost_t cost;    
} tour_struct;
typedef tour_struct* tour_t;


typedef struct {
tour_t* list;
int list_sz;
int list_alloc;
}  stack_struct;
typedef stack_struct* my_stack_t;

【问题讨论】:

  • tour_struct 是一个结构。 tour_t 是一个tour_struct *,也就是说,tour_t 是一个指向被定义为tour_struct的结构体的指针
  • 请注意,end in _t are reserved on POSIX systems 的名称。此外,将指针类型命名为 *_t 充其量是不正当的。

标签: c struct


【解决方案1】:

第一个typedef 给(匿名)结构一个类型名。第二个typedef 定义了一个指向另一个的指针类型。

tour_struct tour; // declares a struct.
tour_t ptr; // declares a pointer to a struct.

【讨论】:

    【解决方案2】:

    第一个 typedef 用于在 C 中声明结构的典型方式。 我猜你指的是第二种typedef: typedef tour_struct* tour_t; 之所以使用它,是因为这里为 a pointer 声明了“另一个名称”(别名),以指向上述声明的结构。这就是使用第二种 typedef 的原因。

    【讨论】:

    • 我可以将我的代码更改为这个并且仍然具有相同的含义。 struct tour_struct { city_t* 城市;整数计数; cost_t 成本; }; struct stack_struct { struct tour_struct *list; int list_sz; int list_alloc; }; struct stack_struct *my_stack_t;
    【解决方案3】:

    typedef 中的已知类型之后使用* 只是定义了一个指向该类型的指针。

    typedef stack_struct* my_stack_t;
    

    将定义一个指向stack_struct 的指针并将其命名为my_stack_t

    【讨论】:

      猜你喜欢
      • 2013-12-23
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      相关资源
      最近更新 更多