使用此代码
#include <stdio.h>
#include <stdlib.h>
struct nodetag {
struct nodetag *next;
struct nodetag *prev;
int a;
};
typedef struct nodetag *node;
int main(void)
{
node h;
printf("%zu\n",sizeof(struct nodetag));
printf("%zu\n",sizeof(*h));
printf("%zu\n",sizeof(*node));
}
Run Code Online (Sandbox Code Playgroud)
编译此代码导致:
expected expression before ‘node’
printf("%u\n",sizeof(*node));
Run Code Online (Sandbox Code Playgroud)
为什么编译器会在 sizeof(*node) 上出错而不是在 sizeof(*h) 上出错?
typedef为其他数据类型创建别名。也就是说,声明
typedef struct nodetag *node;
Run Code Online (Sandbox Code Playgroud)
创建node为struct nodetag *type的别名。
这个说法
sizeof(*node)
Run Code Online (Sandbox Code Playgroud)
与
sizeof(*(struct node *))
Run Code Online (Sandbox Code Playgroud)
您不能取消引用type,因此您在此语句中遇到错误。您可以像在此语句中一样取消引用指针变量
printf("%u\n",sizeof(*h));
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为his 是 typenode的别名struct nodetag *。取消引用h会给struct nodetag.
此外,sizeof运算符的结果类型为size_t。您应该使用%zu格式说明符而不是%u.