結構體強制轉換爲聯合體筆記
測試代碼1
int main()
{
//首先創建一個聯合體,聯合體內有兩個結構體
typedef union
{
struct
{
unsigned int i_ia = 0;
char buffer[32] = "a";
} va_4byte;
struct
{
unsigned int i_ib = 2;
char bufferb[32] = "b";
unsigned int i_ic = 2;
} va_compress;
} union_test;
//測試聯合體的大小:爲40個字節
int i_size = sizeof(union_test);
//打印聯合體大小
printf("%d \n", i_size);
//定義一個結構體,結構體大小爲36個字節
struct MyStruct
{
int abx = 1;
char m_buff[32] = "hello";
} m_struct;
struct MyStruct * p = &m_struct;
//測試結果
printf("ia = %d \n",((union_test*)(p))->va_4byte.i_ia);//1
printf("ia = %s \n", ((union_test*)(p))->va_4byte.buffer);//hello
printf("%d\n", ((union_test*)(p))->va_compress.i_ib);//1
printf("%d\n", ((union_test*)(p))->va_compress.i_ic);//-858993460
printf("%s\n", ((union_test*)(p))->va_compress.bufferb);//hello
強轉後結果分析
- 聯合體具有40個字節大小,結構體只有32個字節
當測試ia的時候,結構體32個字節,正好覆蓋union的前32個字節,所以第一個結構體能夠打印出正確信息
-當測試ib的時候,結構體32個字節,正好覆蓋union的前32個字節,後4個字節沒有覆蓋,所以打印出亂亂的東西。測試代碼2
int main()
{
typedef union
{
struct
{
unsigned int i_ia = 0;
char buffer[32] = "a";
//不相同的地方*****************
struct
{
unsigned int i_ib = 2;
unsigned int i_ic = 2;
char bufferb[32] = "b";
} va_compress;
} union_test;
//**************************
//測試聯合體的大小:爲40個字節
int i_size = sizeof(union_test);
printf("%d \n", i_size);
struct MyStruct
{
int abx = 1;
char m_buff[32] = "hello";
} m_struct;
struct MyStruct * p = &m_struct;
//測試結果
printf("ia = %d \n",((union_test*)(p))->va_4byte.i_ia);//1
printf("ia = %s \n", ((union_test*)(p))->va_4byte.buffer);//hello
printf("%d\n", ((union_test*)(p))->va_compress.i_ib);//1
printf("%d\n", ((union_test*)(p))->va_compress.i_ic);//181043167
printf("%s\n", ((union_test*)(p))->va_compress.bufferb);//o
// return 0;
}
測試結果2
- ia的數據跟原來的一樣
- ib的記錄跟原來一樣
- ic的記錄變爲亂碼
bufferb的記錄,只有一個o,因爲前4個字節被賦值給ib了。
綜上所述:
struct強轉爲union的時候,會從頭開始覆蓋,unicon多出來的部分不進行覆蓋。
如果union比struct小的話,就會被截斷