繁体   English   中英

为什么在 sizeof typedef'ed 指针上 gcc 会出错

[英]Why does gcc error on sizeof typedef'ed pointer

使用此代码

#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));                                                               
}

编译此代码导致:

expected expression before ‘node’  
printf("%u\n",sizeof(*node));  

为什么编译器会在 sizeof(*node) 上出错而不是在 sizeof(*h) 上出错?

typedef为其他数据类型创建别名 也就是说,声明

typedef struct nodetag *node;

创建node作为struct nodetag *类型的别名。
这个说法

sizeof(*node)

sizeof(*(struct node *))

您不能取消引用type ,因此您在此语句中遇到错误。 您可以像在此语句中一样取消引用指针变量

printf("%u\n",sizeof(*h));

这是有效的,因为hnode类型,它是struct nodetag *类型的别名。 struct nodetag引用h将给出struct nodetag

此外, sizeof运算符的结果sizeofsize_t 您应该使用%zu格式说明符而不是%u

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM