[英]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));
這是有效的,因為h
是node
類型,它是struct nodetag *
類型的別名。 struct nodetag
引用h
將給出struct nodetag
。
此外, sizeof
運算符的結果sizeof
為size_t
。 您應該使用%zu
格式說明符而不是%u
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.