C 在typedef结构中指定结构名称

C 在typedef结构中指定结构名称,c,struct,typedef,C,Struct,Typedef,以下两者之间的区别是什么: typedef struct{ uint8 index; uint8 data[256]; }list_t; list_t myList; 及 我正在使用第一种方法,但我在答案上看到了第二种方法。我只想定义类型,并分别用该类型定义变量 第二种方法允许您向前声明结构类型。因此,如果我们处理的是标题,您可以避免不必要的传递包含。例如,考虑这个小标题: // No need to include the header with the ful

以下两者之间的区别是什么:

typedef struct{

    uint8   index;
    uint8   data[256];

}list_t;

list_t myList;


我正在使用第一种方法,但我在答案上看到了第二种方法。我只想定义类型,并分别用该类型定义变量

第二种方法允许您向前声明结构类型。因此,如果我们处理的是标题,您可以避免不必要的传递包含。例如,考虑这个小标题:

// No need to include the header with the full struct definition
// A forward declaration will do
struct list_t;
void foo(struct list_t *);
void bar(void); // Doesn't use list_t
这将删除所有客户端代码对列表的完整定义的依赖关系。只需要使用bar的代码不会通过传递包含强制包含列表的定义


当您使用第一种方法时,您将为一个没有标记的结构类型创建一个别名,因此您不能向前声明它。客户端代码必须包含类型定义才能访问其名称。

这种差异对于自引用数据结构非常有用

typedef struct
{
  int value;
  Example1 *ptr; // error here: the type Example1 is not known yet
} Example1;

typedef struct Example2
{
  int value;
  struct Example2 *ptr; // OK: the type struct Example2 is known
} Example2;

请注意,struct后面的名称不一定与typedef中使用的名称相同。

这似乎是出于品味和首选的编码风格,但其他答案中提到的第二种方式对于自引用结构(如列表或树数据结构和转发声明)非常有用。 至于我,我更喜欢C中的第二种方式,并且认为它更常见

在C中:

在这种情况下,有两个选项:第一个选项是省略typedef和struct_name_t,在这种情况下,要声明一个结构,您需要实际包含struct关键字:

或者,您可以使用typedef声明可以使用的结构名称类型:

struct_name_t struct_instance;
在这两种情况下,如果希望声明指向结构内部结构的指针,则必须使用第一种语法,并使用关键字struct:

struct struct_name *struct_instance;

注意:POSIX保留以_t结尾的标识符。@Alnitak这是什么意思?这意味着如果您正在开发代码以在POSIX兼容平台上编译,您应该将该后缀用于您自己的类型名。哎呀,我的意思是不应该!我真的在想‘如果我已经可以把它用于我自己的类型名,为什么他会提到呢?’哈哈:现在我明白了。谢谢谢谢你,但是。。is struct关键字在struct Example2*ptr;中是必需的吗@snr yes,因为在编译器分析ptr成员的这一点上,类型struct Example2部分被称为前向声明,而不是类型Example2 typedef;后者将在最后一个分号处显示。
struct struct_name struct_instance;
struct_name_t struct_instance;
struct struct_name *struct_instance;