typedef 用于为 C 中的现有类型创建简写符号。它类似于 #define,但不同的是,typedef 由编译器解释,并提供比预处理器更高级的功能。
typedef 的最简单形式为
typedef existing_type new_type;
例如,
typedef unsigned long UnsignedLong;
例如,如果你将size_t 的定义追溯到它的根,你会看到
/* sys/x86/include/_types.h in FreeBSD */
/* this is machine dependent */
#ifdef __LP64__
typedef unsigned long __uint64_t;
#else
__extension__
typedef unsigned long long __uint64_t;
#endif
...
...
typedef __uint64_t __size_t;
然后
/* stddef.h */
typedef __size_t size_t;
这实际上意味着,size_t 是 unsigned long long 的别名,具体取决于您的机器具有的 64 位模式(LP64、ILP64、LLP64)。
对于您的问题,您尝试定义一个新类型但没有命名它。不要让struct item {..} 定义混淆您,它只是您要声明的类型。如果你用一个基本类型替换整个struct item {...},比如用int,然后重写你的typedef,你最终会得到这样的结果
typedef int; /* new type name is missing */
正确的形式应该是
typedef struct item {...} Item;
请参阅下面的示例了解不同的结构定义
#include <stdio.h>
/* a new type, namely Item, is defined here */
typedef struct item_t {
char *text;
int count;
struct item_t *next; /* you canot use Item here! */
} Item;
/* a structure definition below */
struct item {
char *text;
int count;
struct item *next;
};
/* an anonymous struct
* However, you cannot self-refence here
*/
struct {
int i;
char c;
} anon;
int main(void) {
/* a pointer to an instance of struct item */
struct item *pi;
/* Shorthand for struct item_t *iI */
Item *iI;
/* anonymoous structure */
anon.i = 9;
anon.c = 'x';
return 0;
}