[英]Sizeof() of pointer pointing to NULL
以下是我的代碼:
#include <stdio.h>
struct abc
{
char a;
int b;
};
int main()
{
struct abc *abcp = NULL;
printf("%d", sizeof(*abcp)); //Prints 8
/* printf("%d",*abcp); //Causes program to hang or terminate */
return 0;
}
我了解由於結構填充,結構的大小為8。 但是,當為'abcp'分配為NULL時,為什么'* abcp'的sizeof()提供一個值? 如果將'abcp'分配為NULL,則表示它沒有指向任何地方嗎? 但是,為什么我得到上面代碼的輸出?
sizeof
是運算符,而不是函數。
如果您刪除了無意義的括號並寫下了它,將會使您想起:
printf("%zu", sizeof *abcp);
這也使用C99-property方式格式化size_t
類型的值,即%zu
。
由於編譯器在編譯時計算大小,因此無需跟蹤(當然也不會引用)指針(因為指針尚不存在;程序未運行),因此它可以工作。
sizeof
不是函數,也不評估其參數。 相反,它在編譯時推導*abcp
的類型,並報告其大小。 由於abcp
是struct abc*
,因此*abcp
的類型為struct abc
而不管abcp
指向何處。
從C99標准
6.5.3.4/2
The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.
給定Type *var
,以下表達式是等效的:
sizeof(Type)
sizeof(*var)
sizeof(var[N]) // for any constant integer expression N
sizeof(var[n]) // for any variable integer expression n
這些表達式中的每個表達式在編譯期間都解析為一個常數。
因此,運行時var
的值對這些表達式之一均無效。
sizeof
只是返回* abcp的大小,並且該指針在您的計算機中的大小為8。 指針中存儲的地址是否有效並不重要( NULL
通常是無效地址)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.