有什么好的例子可以说明结构体和联合体的区别吗? 基本上我知道struct使用了它成员的所有内存,而union使用了最大的成员内存空间。还有其他操作系统级别的差异吗?
当前回答
联合的用法 当需要特殊类型的对话时,联合经常被使用。 来了解联合的用处。c/c标准库没有定义专门为将短整数写入文件而设计的函数。使用fwrite()会导致简单操作的开销过大。然而,使用联合可以很容易地创建一个函数,该函数将一个短整数的二进制每次一个字节写入文件。我假设短整数是2字节长
示例:
#include<stdio.h>
union pw {
short int i;
char ch[2];
};
int putw(short int num, FILE *fp);
int main (void)
{
FILE *fp;
fp fopen("test.tmp", "wb ");
putw(1000, fp); /* write the value 1000 as an integer*/
fclose(fp);
return 0;
}
int putw(short int num, FILE *fp)
{
pw word;
word.i = num;
putc(word.c[0] , fp);
return putc(word.c[1] , fp);
}
虽然我用短整数调用putw(),但可以使用putc()和fwrite()。但是我想展示一个例子来说明如何使用联合
其他回答
结构分配其中所有元素的总大小。
一个联合只分配它最大的成员所需要的内存。
结构是不同数据类型的集合,其中可以驻留不同类型的数据 每一个都有自己的内存块。
当我们确定一次只使用其中一个变量,并且希望充分利用当前内存时,我们通常使用联合,因为它只获得一个等于最大类型的内存块。
struct emp
{
char x; //1 byte
float y; //4 byte
} e;
它获得的总内存:=>5字节。
union emp
{
char x; //1 byte
float y; //4 byte
} e;
它获得的总内存:4字节。
联合的用法 当需要特殊类型的对话时,联合经常被使用。 来了解联合的用处。c/c标准库没有定义专门为将短整数写入文件而设计的函数。使用fwrite()会导致简单操作的开销过大。然而,使用联合可以很容易地创建一个函数,该函数将一个短整数的二进制每次一个字节写入文件。我假设短整数是2字节长
示例:
#include<stdio.h>
union pw {
short int i;
char ch[2];
};
int putw(short int num, FILE *fp);
int main (void)
{
FILE *fp;
fp fopen("test.tmp", "wb ");
putw(1000, fp); /* write the value 1000 as an integer*/
fclose(fp);
return 0;
}
int putw(short int num, FILE *fp)
{
pw word;
word.i = num;
putc(word.c[0] , fp);
return putc(word.c[1] , fp);
}
虽然我用短整数调用putw(),但可以使用putc()和fwrite()。但是我想展示一个例子来说明如何使用联合
在编写下面给出的字节排序函数时,联合非常方便。这在结构体中是不可能的。
int main(int argc, char **argv) {
union {
short s;
char c[sizeof(short)];
} un;
un.s = 0x0102;
if (sizeof(short) == 2) {
if (un.c[0] == 1 && un.c[1] == 2)
printf("big-endian\n");
else if (un.c[0] == 2 && un.c[1] == 1)
printf("little-endian\n");
else
printf("unknown\n");
} else
printf("sizeof(short) = %d\n", sizeof(short));
exit(0);
}
// Program from Unix Network Programming Vol. 1 by Stevens.
Union不同于struct,因为Union在其他的上面重复:它重新定义同一个内存,而struct一个接一个地定义,没有重叠或重定义。