简体   繁体   中英

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) ?

typedef creates an alias name for other data type. That means, the statement

typedef struct nodetag *node;

creates node as an alias of struct nodetag * type.
This statement

sizeof(*node)

is same as

sizeof(*(struct node *))

You cannot dereference a type , hence you are getting error on this statement. 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. Dereferencing h will give struct nodetag .

Also, the type of the result of sizeof operator is size_t . You should use %zu format specifier instead of %u .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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