简体   繁体   English

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

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

Working with this code使用此代码

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

Compiling this code results in:编译此代码导致:

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

Why does the compiler error on sizeof(*node) but not on sizeof(*h) ?为什么编译器会在 sizeof(*node) 上出错而不是在 sizeof(*h) 上出错?

typedef creates an alias name for other data type. typedef为其他数据类型创建别名 That means, the statement也就是说,声明

typedef struct nodetag *node;

creates node as an alias of struct nodetag * type.创建node作为struct nodetag *类型的别名。
This statement这个说法

sizeof(*node)

is same as

sizeof(*(struct node *))

You cannot dereference a type , hence you are getting error on this statement.您不能取消引用type ,因此您在此语句中遇到错误。 You can dereference a pointer variable as you are doing in this statement您可以像在此语句中一样取消引用指针变量

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

This is valid as the h is of type node which is an alias of struct nodetag * type.这是有效的,因为hnode类型,它是struct nodetag *类型的别名。 Dereferencing h will give struct nodetag . struct nodetag引用h将给出struct nodetag

Also, the type of the result of sizeof operator is size_t .此外, sizeof运算符的结果sizeofsize_t You should use %zu format specifier instead of %u .您应该使用%zu格式说明符而不是%u

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

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