定义一个联合类型的一般形式为:
union 联合名
{
成员表
};
例如:
union w
{
int a;
char b;
};
联合定义之后,即可进行联合变量说明,被说明为w类型的变量,可以存放整型量a或存放字符数组b。
二、联合变量的说明
联合变量的说明和结构变量的说明方式相同, 也有三种形式。即先定义,再说明;定义同时说明和直接说明。以w类型为例,说明如下:
union w
{
int a;
char b;
};
union w c,d;
或者可同时说明为:
union w
{
int a;
char b;
}c,d;
或直接说明为:
union
{
int a;
char b;
}c,d
union中的成员变量,因为共享同一快内存区域,所以要么赋予整型值,要么赋予字符串,不能把两者同时赋予它。
union存在的情形:我们常常使用几个变量,但其中只有一个变量在任意给定的时刻有有效值。
另一种情形:程序处理许多不同类型数据,但是一次只能处理一种,要处理的类型在执行期间确定。
再一种:要在不同的时间访问相同的数据,但在不同的情况下该数据的类型是不同的。
判断cup是big_endian or little_endian
- #include<stdio.h>
- int checkCPU(){
- union {
- int a;
- char b;
- }c;
- c.a=1;
- return (c.b==1);
- }
- int main(){
- int a =0 ;
- a=checkCPU();
- printf("%d",a);
- }
- int checkCPU(){
- int i = 1;
- return *((char*)&i)==1 ? 1 : 0;
- }
We've defined a word to mean 32 bits. This is the same as 4 bytes. Integers, single-precision floating point numbers, and MIPS instructions are all 32 bits long. How can we store these values into memory? After all, each memory address can store a single byte, not 4 bytes.
我们知道一个整型占4字节,32位,应该怎么在内存中存储呢,每个内存空间存储一个字节,不是4个
The answer is simple. We split the 32 bit quantity into 4 bytes. For example, suppose we have a 32 bit quantity, written as 90AB12CD16, which is hexadecimal. Since each hex digit is 4 bits, we need 8 hex digits to represent the 32 bit value.
答案是简单的,我们可以分成4个连续的内存区域,比如十六进制数 90AB12CD
So, the 4 bytes are: 90, AB, 12, CD where each byte requires 2 hex digits.
It turns out there are two ways to store this in memory
于是分为下面两个存储方式:
Big Endian
In big endian, you store the most significant byte in the smallest address. Here's how it would look:
Address | Value |
1000 | 90 |
1001 | AB |
1002 | 12 |
1003 | CD |
Little Endian
In little endian, you store the least significant byte in the smallest address. Here's how it would look:
Address | Value |
1000 | CD |
1001 | 12 |
1002 | AB |
1003 | 90 |
LSB 最低有效位;least significant bit
MSB最高有效位 most significant bit
变量类型所占的内存空间取决于所使用的编译器
操作系统的位数: