首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C 語言關鍵字 sizeof 深度解析:用法、類型大小與對齊規則

     編輯:關於C語言

sizeof 是 C 語言的一元運算子(非函數),在編譯期或執行期計算型別或運算式佔用的位元組數,返回型別為 size_t(定義於 <stddef.h>)。本文全面整理其語法、限制、常見型別大小(32 位元系統)、結構體對齊規則與實測程式碼。

語法形式

sizeof unary-expression
sizeof (type-name)

不可使用的場合

  • 函數型別或不完整型別的運算式
  • 此類型別的括號名稱
  • 位元欄位成員

變長陣列 (VLA) 特例

若運算元為 VLA,sizeof 會在執行期求值(副作用生效);否則為編譯期常量,不求值。

實用範例

  • 記憶體分配:dp = alloc(sizeof *dp);
  • 計算陣列元素數:sizeof array / sizeof array[0]
  • VLA 大小計算:int b[n+3]; sizeof b;

ANSI C 規定與 32 位元系統常見大小

基本型別

型別大小(位元組)
_Bool1
char1
short2
int4
long4
long long8
float4
double8
long double12
_Complex16
void1 (GNU 延伸)

指標、枚舉

  • 指標:4 位元組
  • 枚舉:4 位元組

陣列

陣列長度 * 成員大小

結構體對齊規則

  1. 對齊值 ALIGN = #pragma pack(n) 指定值或預設最大成員大小。
  2. 每個成員相對結構體起始位移必須為 min(ALIGN, 成員大小) 的整數倍,必要時在成員間插入填充位元組。
  3. 結構體總大小必須為 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 代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved