回复 7楼 TonyDeng
您的话如当头棒喝。
#include <stdio.h> #include <conio.h> typedef union _myUnion { int i[4]; long k; char c[6]; } myUnion; void show_UnionMapping(const myUnion *theUnion); void main(void) { myUnion a = {0}; printf_s("结构体的尺寸 = %dByte\n", sizeof(a)); printf_s("\n开始时内存:\n"); show_UnionMapping(&a); a.i[1] = 0x61; printf_s("\n赋值后内存:\n"); show_UnionMapping(&a); printf_s("\n输出:c[1]=%c c[%d]=%c\n", a.c[1], sizeof(a.i[0]), a.c[sizeof(a.i[0])]); _getch(); } void show_UnionMapping(const myUnion *theUnion) { char* p = (char *)theUnion; for (size_t index = 0; index != sizeof(*theUnion); ++index) { printf_s("%x ", *p); ++p; } printf_s("\n"); }
#include <stdio.h> #include <conio.h> typedef union _myUnion { short i[4]; long k; char c[6]; } myUnion; void show_UnionMapping(const myUnion *theUnion); void main(void) { myUnion a = {0}; printf_s("结构体的尺寸 = %dByte\n", sizeof(a)); printf_s("\n开始时内存:\n"); show_UnionMapping(&a); a.i[1] = 0x61; printf_s("\n赋值后内存:\n"); show_UnionMapping(&a); printf_s("\n输出:c[1]=%c c[%d]=%c k=%x\n", a.c[1], sizeof(a.i[0]), a.c[sizeof(a.i[0])], a.k); _getch(); } void show_UnionMapping(const myUnion *theUnion) { char* p = (char *)theUnion; for (size_t index = 0; index != sizeof(*theUnion); ++index) { printf_s("%x ", *p); ++p; } printf_s("\n"); }