可能重复:
结构的用途,typedef struct,在 C++
typedef struct vs struct 定义中
我知道在 C 中有两种声明结构的方法
struct point{
int x, y;
};
和:
typedef struct{
int x, y;
} point;
但这两种方法有什么区别,我什么时候使用 typedef 方法而不是其他方法?
可能重复:
结构的用途,typedef struct,在 C++
typedef struct vs struct 定义中
我知道在 C 中有两种声明结构的方法
struct point{
int x, y;
};
和:
typedef struct{
int x, y;
} point;
但这两种方法有什么区别,我什么时候使用 typedef 方法而不是其他方法?
区别:
point p;
与第二个一起使用。struct
在C中只有一种声明 a的方法,使用struct
关键字,可选地后跟结构名称,然后是大括号中的成员字段列表。所以你可以有:
struct point_st {
int x, y;
};
这point_st
是您的结构的名称(或标签)。请注意,结构名称在 C 中的命名空间与类型不同(这在 C++ 中不同)。所以我习惯用_st
如上所示的结构名称后缀。
您可以(独立地)使用 typedef 定义类型名称,例如
typedef struct point_st Point;
(您可以typedef
在任何 C 类型上使用,顺便说一句)。
例如 Gtk 和 Glib 有很多不透明的类型,它们就是这样的不透明结构;只有实现知道并关心结构成员。
当然编译器需要知道结构的字段来分配它;但如果您只使用指向不透明结构的指针,则无需声明该结构(即大括号中的字段)。
对于第一种形式,变量声明必须是:
struct point A;
第二种形式允许声明变量而struct
不像
point B;