前言
C語言中的sizeof是一個很有意思的關鍵字,經常有人用不對,搞不清不是什么。我以前也有用錯的時候,現在寫一寫,也算是提醒一下自己吧。
sizeof是什么
sizeof是C語言的一種單目操作符,如C語言的其他操作符++、--等,sizeof操作符以字節形式給出了其操作數的存儲大小。操作數可以是一個表達式或括在括號內的類型名。這個操作數不好理解對吧?后面慢慢看就明白了。sizeof的返回值是size_t,在64位機器下,被定義為long unsigned int。
sizeof函數的結果:
1.變量:變量所占的字節數。
int i = 0;printf("%d/n", sizeof(i)); //4
2.數組:數組所占的字節數。
int arr_int1[] = {1,2,3,4,5};int arr_int2[10] = {1,2,3,4,5};printf("size_arr1=%d/n",sizeof(arr_int1)); //5*4=20 printf("size_arr2=%d/n",sizeof(arr_int2)); //10*4=40
3.字符串:其實就是加了'/0'的字符數組。結果為字符串字符長度+1。
char str[] = "str";printf("size_str=%d/n",sizeof(str)); //3+1=4
4.指針:固定長度:4(32位地址環境)。
特殊說明:數組作為函數的入口參數時,在函數中對數組sizeof,獲得的結果固定為4:因為傳入的參數是一個指針。
int Get_Size(int arr[]) { return sizeof(arr);}int main() { int arr_int[10] = {1,2,3,4,5}; printf("size_fun_arr=%d/n",Get_Size(arr_int)); //4}
5.結構體
1.只含變量的結構體:
結果是最寬變量所占字節數的整數倍:[4 1 x x x ]
typedef struct test { int i; char ch;}test_t;printf("size_test=%d/n", sizeof(test_t)); //8
幾個寬度較小的變量可以填充在一個寬度范圍內:[4 2 1 1]
typedef struct test { int i; short s; char ch1; char ch2;}test_t;printf("size_test=%d/n", sizeof(test_t)); //8
地址對齊:結構體成員的偏移量必須是其自身寬度的整數倍:[4 1 x 2 1 x x x]
typedef struct test { int i; char ch1; short s; char ch2;}test_t;printf("size_test=%d/n", sizeof(test_t)); //12
2.含數組的結構體:包含整個數組的寬度。數組寬度上文已詳述。[4*10 2 1 1]
typedef struct test { int i[10]; short s; char ch1; char ch2;}test_t;printf("size_test=%d/n", sizeof(test_t)); //44
3.嵌套結構體的結構體
包含整個內部結構體的寬度(即整個展開的內部結構體):[4 4 4]
typedef struct son { int name; int birthday; }son_t; typedef struct father { son_t s1; int wife;}father_t;printf("size_struct=%d/n",sizeof(father_t)); //12
地址對齊:被展開的內部結構體的 首個成員的偏移量 ,必須是被展開的 內部結構體中最寬變量 所占字節的整數倍:[2 x x 2 x x 4 4 4]
typedef struct son { short age; int name; int birthday; }son_t; typedef struct father { short age; son_t s1; int wife;}father_t;printf("size_struct=%d/n",sizeof(father_t)); //20
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答