Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

C 語言 sizeof() 求各型別位元組數實測整理

本文盡可能完整地測試了在 Win32 平台下使用 sizeof() 求各類變數位元組數的結果,並持續更新,對釐清型別大小很有參考價值。

基本型別

sizeof(char)            = 1
sizeof(short)           = 2
sizeof(int)             = 4
sizeof(long)            = 4
sizeof(float)           = 4
sizeof(double)          = 8
sizeof(long double)     = 8

sizeof(unsigned char)   = 1
sizeof(unsigned short)  = 2
sizeof(unsigned int)    = 4
sizeof(unsigned long)   = 4

陣列與指標

字元陣列的大小取決於元素數量與是否含字串結尾的 '\0';而無論指向何種資料,指標本身在 32 位元平台一律為 4 位元組。

char a[] = {'a','b','c','d','e'};        // sizeof(a) = 5
char b[] = "abcde";                       // sizeof(b) = 6(含結尾 '\0')
char c[][3] = {{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'}};
// sizeof(c) = 12, sizeof(c[0]) = 3, sizeof(c[0][0]) = 1
char d[][5] = {"abcc","deff","ghii","jkll"};
// sizeof(d) = 20, sizeof(d[0]) = 5, sizeof(d[0][0]) = 1

char *p = 0;                              // sizeof(p) = 4
char *q = (char *)malloc(5);              // sizeof(q) = 4
char *r = "abcde";                        // sizeof(r) = 4
char (*f)(void) = NULL;                   // sizeof(f) = 4

指標陣列與二維陣列

char *s1[3] = {"aa","bb","cc"};
// sizeof(s1) = 12, sizeof(s1[0]) = 4, sizeof(*s1[0]) = 1

char *s2[3][3] = {{"aa","bb","cc"},{"aa","bb","cc"},{"aa","bb","cc"}};
// sizeof(s2) = 36, sizeof(s2[0]) = 12, sizeof(*s2[0]) = 4

char h[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
char (*ph)[3] = h;
// sizeof(ph) = 4, sizeof(*ph) = 3, sizeof(ph[0]) = 3, sizeof(*ph[0]) = 1

由這些實測結果可見,sizeof 回傳的是型別本身所占的位元組數:陣列回傳整體大小,指標則恆為固定長度。理解這點,有助避免動態記憶體與指標運算上的常見錯誤。

Copyright © Linux教程網 All Rights Reserved