Unions
共同体
C Unions与C Structures基本相同,不同之处在于Union不允许包含多个变量,每个变量都有自己的内存,而Union允许同一个变量使用多个名称。这些名称可以将内存视为不同的类型(并且联合的大小将是最大类型的大小,+编译器可能决定给它的任何填充)
因此,如果您希望能够以不同的方式读取变量的内存,例如一次读取整数一个字节,您可以使用以下内容:
union intParts {
int theInt;
char bytes[sizeof(int)];
};
允许您单独查看每个字节而不使用指针并使用指针算法:
union intParts parts;
parts.theInt = 5968145; // arbitrary number > 255 (1 byte)
printf("The int is %i\nThe bytes are [%i, %i, %i, %i]\n",
parts.theInt, parts.bytes[0], parts.bytes[1], parts.bytes[2], parts.bytes[3]);
// vs
int theInt = parts.theInt;
printf("The int is %i\nThe bytes are [%i, %i, %i, %i]\n",
theInt, *((char*)&theInt+0), *((char*)&theInt+1), *((char*)&theInt+2), *((char*)&theInt+3));
// or with array syntax which can be a tiny bit nicer sometimes
printf("The i