struct与union的区别与联系

union ( 共用体):构造数据类型,也叫联合体 
 用途:使几个不同类型的变量共占一段内存(相互覆盖)


 struct ( 结构体 ):是一种构造类型
 用途: 把不同的数据组合成一个整体——自定义数据类型


主要区别:
1. struct和union都是由多个不同的数据类型成员组成, 但在任何同一时刻, union中只存放了一个被选中的成员; 而struct的所有成员都存在。在struct中,各成员都占有自己的内存空间,它们是同时存在的,一个struct变量的总长度等于所有成员长度之和,遵从字节对齐原则; 在Union中,所有成员不能同时占用它的内存空间,它们不能同时存在 , Union变量的长度等于最长的成员的长度

2. 对于union的不同成员赋值, 将会对其它成员重写, 原来成员的值就不存在了,所以,共同体变量中起作用的成员是最后一次存放的成员; 而对于struct的不同成员赋值是互不影响的。


#include <stdio.h> 
#include <stdlib.h>
#include <conio.h>
#include<cstdlib>  //system.pause()所包含的头文件
#include <iostream>
using namespace std;

void main()
{
	union
	{
		int i;
		struct
		{
			char first;
			char second;
			char third;
			char fourth;
		}half;
	}number;

	number.i = 2008;
	printf("%d\n%d\n%d\n%d\n", number.half.first, number.half.second, number.half.third, number.half.fourth);
	printf("%d\n", number.i);

	number.half.first = 1;
	number.half.second = 2;
	number.half.third = 4;
	number.half.fourth = 8;
	printf("%d\n%d\n%d\n%d\n", number.half.first, number.half.second, number.half.third, number.half.fourth);
	printf("%d\n", number.i);

	number.i = 2018;
	printf("%d\n%d\n%d\n%d\n", number.half.first, number.half.second, number.half.third, number.half.fourth);
	printf("%d\n", number.i);
	system("pause");
	//    getch();
}

结果为:

-40
7
0
0
2008
1
2
4
8
134480385
-30
7
0
0
2018

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值