sizeof 運算子
出自 cppreference.com
查詢物件或類型的尺寸。
用於必須得知物件實際尺寸的場合。
目錄 |
[編輯] 語法
sizeof( 類型 ) |
(1) | ||||||||
sizeof 表達式 |
(2) | ||||||||
兩種版本都會回傳 size_t 類型的值。
[編輯] 解釋
2) 回傳 表達式 之類型所對應的物件表示大小(以位元組為單位)。不會對 表達式 進行隱式型別轉換。
[編輯] 附註
根據電腦架構,一個位元組 (byte) 可能由 8 個或更多位元組成,其確切數量由 CHAR_BIT 提供。
sizeof(char)、sizeof(signed char) 與 sizeof(unsigned char) 總是回傳 1。
sizeof 不能用於函式類型、不完整類型(包括 void)或位元欄位 (bit-field) 左值。
當作用於具有結構 (structure) 或聯合 (union)類型的運算元時,結果為該物件的總位元組數,包括內部與結尾的填補 (padding)。結尾填補的設置方式是:若該物件作為陣列元素,下一個元素的對齊需求將會被滿足;換言之,sizeof(T) 會回傳 T[] 陣列中一個元素的大小。
|
若 類型 為 VLA(變長陣列)類型,且改變其尺寸表達式的值不會影響 |
(自 C99 起) |
除非 表達式 的類型為 VLA,(C99 起)否則 表達式 不會被求值,且 sizeof 運算子可用於整數常數表達式中。
|
若 表達式 的類型為 變長陣列 (variable-length array) 類型,則會對 表達式 求值,並在執行期間計算出該陣列的尺寸。 |
(自 C99 起) |
任何陣列 a(包括 VLA(C99 起))中的元素數量,皆可透過表達式 sizeof a / sizeof a[0] 來確定。請注意,若 a 為指標類型(例如在陣列轉指標轉換或函式參數類型調整之後),此表達式將僅是計算指標類型的位元組數除以所指向類型的位元組數。
[編輯] 關鍵字
[編輯] 範例
範例輸出對應於 64 位元指標與 32 位元 int 的平台
執行此程式碼
#include <stdio.h> int main(void) { short x; // type argument: printf("sizeof(float) = %zu\n", sizeof(float)); printf("sizeof(void(*)(void)) = %zu\n", sizeof(void(*)(void))); printf("sizeof(char[10]) = %zu\n", sizeof(char[10])); // printf("sizeof(void(void)) = %zu\n", sizeof(void(void))); // Error: function type // printf("sizeof(char[]) = %zu\n", sizeof(char[])); // Error: incomplete type // expression argument: printf("sizeof 'a' = %zu\n", sizeof 'a'); // type of 'a' is int // printf("sizeof main = %zu\n", sizeof main); // Error: Function type printf("sizeof &main = %zu\n", sizeof &main); printf("sizeof \"hello\" = %zu\n", sizeof "hello"); // type is char[6] printf("sizeof x = %zu\n", sizeof x); // type of x is short printf("sizeof (x+1) = %zu\n", sizeof(x + 1)); // type of x+1 is int }
可能輸出
sizeof(float) = 4 sizeof(void(*)(void)) = 8 sizeof(char[10]) = 10 sizeof 'a' = 4 sizeof &main = 8 sizeof "hello" = 6 sizeof x = 2 sizeof (x+1) = 4
[編輯] 參考資料
- C23 標準 (ISO/IEC 9899:2024)
- 6.5.3.4 The sizeof and alignof operators (頁碼:待定)
- C17 標準 (ISO/IEC 9899:2018)
- 6.5.3.4 The sizeof and _Alignof operators (頁碼:待定)
- C11 標準 (ISO/IEC 9899:2011)
- 6.5.3.4 sizeof 與 _Alignof 運算子 (p: 90-91)
- C99 標準 (ISO/IEC 9899:1999)
- 6.5.3.4 The sizeof operator (頁碼:80-81)
- C89/C90 標準 (ISO/IEC 9899:1990)
- 3.3.3.4 The sizeof operator
[編輯] 參見
| C++ 文件 關於
sizeof 運算子 |