联合体

本文通过具体的C++代码示例,详细介绍了结构体(struct)与联合体(union)的使用方法及其内存布局特点。通过对不同结构体和联合体的定义与实例化,展示了它们在内存中所占空间大小及地址的输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>


#include<string>
using namespace std;


struct s1{
union u{
int i;
};
struct ss1{
int i;
};
};


struct s2{
union{
int i;
};
struct{
int i;
};
};


struct s3{//the same to s2  
union su3{
int i;
}su33;
struct ss3{
int i;
}ss33;
};


union su4{
int i;
};
struct ss4{
int i;
};
struct s4{//the same to s3  
union su4 su44;
struct ss4 ss44;
};
struct s5{//the same to s1  
union su4;
struct ss4;
};


/* struct s6{//the same to s1  
union{
int;
};
struct{
int;
};
};
*/


int main(){
#include <stdio.h>  
struct s1 sVal1;
struct s2 sVal2;
struct s3 sVal3;
struct s4 sVal4;
struct s5 sVal5;
//struct s6 sVal6;


printf("sVal1's size:%d\n", sizeof(sVal1));
printf("sVal1:%p\t%d\n", &sVal1);


printf("sVal2's size:%d\n", sizeof(sVal2));
printf("sVal2:%p\t%d\n", &sVal2);


printf("sVal3's size:%d\n", sizeof(sVal3));
printf("sVal3:%p\t%d\n", &sVal3);


printf("sVal4's size:%d\n", sizeof(sVal4));
printf("sVal4:%p\t%d\n", &sVal4);


printf("sVal5's size:%d\n", sizeof(sVal5));
printf("sVal5:%p\t%d\n", &sVal5);


printf("sVal5's size:%d\n", sizeof(sVal5));
printf("sVal5:%p\t%d\n", &sVal5);


system("pause");


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值