1. 程式人生 > >結構體偏移量(sizeof長度)的簡單研究

結構體偏移量(sizeof長度)的簡單研究

long long size 一個 eof sig stdio.h 輸出結果 答案 cnblogs

總能夠網上搜到這樣的,關於結構體sizeof的答案,然而,經過這個簡單的實驗以後,發現gcc5.3編譯的結果並非如此。

字節對齊的細節和具體編譯器實現相關,但一般而言,滿足三個準則:

1. 結構體變量的首地址能夠被其最寬基本類型成員的大小所整除;

2. 結構體每個成員相對於結構體首地址的偏移量都是成員大小的整數倍,如有需要編譯器會在成員之間加上填充字節;

3. 結構體的總大小為結構體最寬基本類型成員大小的整數倍,如有需要編譯器會在最末一個成員之後加上填充字節。

#include <stdio.h>

typedef unsigned char U8;
typedef unsigned short U16;
typedef unsigned int U32;
typedef unsigned long long U64;

typedef struct type1{
	U8 size8;
	U32 size32;
	U16 size16;
}type1;

typedef struct type2{
	U8 size8;  U16 size16;
	U32 size32;
}type2;

int main(int argc, char * argv[]){

	U8 size8;  U16 size16;  U32 size32;  U64 size64;
	printf("U8:%d, U16:%d, U32:%d, U64:%d\n", 
		sizeof(size8), sizeof(size16), sizeof(size32), sizeof(size64));

	printf("type1:%d\ttype2:%d\n", sizeof(type1), sizeof(type2));
	return 0;
}

  輸出結果如下:

U8:1, U16:2, U32:4, U64:8
type1:12        type2:8

結構體偏移量(sizeof長度)的簡單研究