sizeof 是 C 語言的一元運算子(非函數),在編譯期或執行期計算型別或運算式佔用的位元組數,返回型別為 size_t(定義於 <stddef.h>)。本文全面整理其語法、限制、常見型別大小(32 位元系統)、結構體對齊規則與實測程式碼。
sizeof unary-expression sizeof (type-name)
若運算元為 VLA,sizeof 會在執行期求值(副作用生效);否則為編譯期常量,不求值。
dp = alloc(sizeof *dp);sizeof array / sizeof array[0]int b[n+3]; sizeof b;| 型別 | 大小(位元組) |
|---|---|
_Bool | 1 |
char | 1 |
short | 2 |
int | 4 |
long | 4 |
long long | 8 |
float | 4 |
double | 8 |
long double | 12 |
_Complex | 16 |
void | 1 (GNU 延伸) |
陣列長度 * 成員大小
ALIGN = #pragma pack(n) 指定值或預設最大成員大小。min(ALIGN, 成員大小) 的整數倍,必要時在成員間插入填充位元組。min(ALIGN, 最大成員大小) 的整數倍,必要時在末尾填充。規則類似結構體,大小為最大成員對齊後的大小。
#include <stdio.h>
#include <complex.h>
#define SIZEOF(x) printf("size of '%s' is %zu\n", #x, sizeof(x))
int main() {
SIZEOF(char); SIZEOF(short); SIZEOF(int); SIZEOF(long);
SIZEOF(long long); SIZEOF(float); SIZEOF(double); SIZEOF(long double);
SIZEOF(_Complex); SIZEOF(void*); SIZEOF(int(*)());
SIZEOF(int[10]); SIZEOF(int[2][3]);
SIZEOF(struct { char c; short s; });
SIZEOF(struct { int i; char c; });
#pragma pack(push, 1)
SIZEOF(struct { int i; char c; });
#pragma pack(pop)
SIZEOF(struct { double d; char c; });
SIZEOF(struct { int c1:1; int :0; int c2:3; });
SIZEOF(struct { int i:3; char c; });
SIZEOF(struct { struct { short s1; char c; }; char c2; });
SIZEOF(struct { short s1; char c1; });
SIZEOF(struct { char c2; struct { short s1; char c1; }; });
SIZEOF(struct { char c; int i; });
return 0;
}
編譯執行即可查看當前平台各型別實際大小,驗證對齊規則。
sizeof 是靜態分析與動態記憶體管理的基石。熟記基本型別大小、掌握結構體對齊規則、善用 sizeof array / sizeof *array 計算元素數、注意 VLA 求值特性,能讓你寫出更可移植、更安全的 C 代碼。