当前位置:网站首页>union中有struct的情况-从内存分析
union中有struct的情况-从内存分析
2022-07-30 05:39:00 【Linke66】
union中的每个成员共用一块内存,且首地址相同;
这块内存必须大于等于union中最大成员的字节数。
举个例子:
union U中有两个成员,
一个是int型的a,4个字节;
一个是结构体STU,考虑对齐,16个字节。
struct STU {
int b;
long long c;
};
union U{
int a;
STU stu;
};
首先使用结构体初始化union U,查看其内存分布情况:
U u;
STU m_stu;
m_stu.b = 6;
m_stu.c = 66;
u.stu = m_stu;
cout << "struct 中 (int)b=" << u.stu.b << " (long)c=" << u.stu.c << endl;
内存分布情况如下图,union的初始地址是0x007CF9E8,分配了16个字节的内存;
前面4个字节存放成员(int)b,后面四个字节是对齐的4个字节;
再往后面8个字节的内存存放(long long)c;
所以b=6;c=66;
下面用union另一个成员(int)a来初始化union U;
u.a = INT_MAX;
cout << "(int)a=" << u.a << endl;
cout << "struct 中 (int)b=" << u.stu.b << " (long)c=" << u.stu.c << endl;
内存中的情况如下图
所以输出为:
下面做一个测试,考虑以下代码
现在union中两个成员,结构体STU类型的stu和int型的a都为4个字节;
我们先初始化stu的四个成员为字符’a’,那么查看stu的四个字符成员,自然都是’a’;
接下来我们将使用union U中的a成员,初始化为1111638594,即16进制的 42 42 42 42,而字符’B’的ascii码为42(16进制),那么这个时候假如我们去输出结构体的4个成员,它会是什么呢?结果在下面。
struct STU {
char ch1;
char ch2;
char ch3;
char ch4;
};
union U{
int a;
STU stu;
};
int main() {
U u;
STU m_stu;
m_stu.ch1 = 'a'; //ascii为97,即16进制61
m_stu.ch2 = 'a';
m_stu.ch3 = 'a';
m_stu.ch4 = 'a';
u.stu = m_stu;
cout << "struct 中 (char)ch1=" << u.stu.ch1
<< " (char)ch2=" << u.stu.ch2
<< " (char)ch3=" << u.stu.ch3
<< " (char)ch4=" << u.stu.ch4
<< endl;
u.a = 1111638594;//16进制为 42 42 42 42 ,ascii为42对应的字符是B
cout << "(int)a=" << u.a << endl;
cout << "struct 中 (char)ch1=" << u.stu.ch1
<< " (char)ch2=" << u.stu.ch2
<< " (char)ch3=" << u.stu.ch3
<< " (char)ch4=" << u.stu.ch4
<< endl;
}
根据上面的分析,我们不难分析出,这时候输出结构体的4个成员,都是字符‘B’
边栏推荐
- flask的笔记
- 453.最小操作数使数组元素相等
- 665.非递减数列
- 手把手教你设计一个CSDN系统
- [GO语言基础] 一.为什么我要学习Golang以及GO语言入门普及
- G Bus Count (Google Kickstart2014 Round D Problem B) (DAY 89)
- Solve the problem that the local nacos is not configured but the localhost8848 connection exception always occurs
- postman 请求 post 调用 传 复合 json数据
- 分布式事务之 Atomikos 原理和使用(一)
- MySql的初识感悟,以及sql语句中的DDL和DML和DQL的基本语法
猜你喜欢

“tensorflow.keras.preprocessing“ has no attribute “image_dataset_from_directory“

MySQL-Explain详解

cnpm安装步骤

Navicat new database

Navicat connection MySQL error: 1045 - Access denied for user 'root'@'localhost' (using password YES)

手把手教你彻底卸载MySQL

微积分 / 自动求导

ClickHouse data insert, update and delete operations SQL

Teach you how to design a CSDN system

Graphic mirror symmetry (schematic diagram)
随机推荐
【Pytorch】torch.manual_seed()、torch.cuda.manual_seed() 解释
分布式事务之 Atomikos 原理和使用(一)
MySQL 用户授权
Anaconda安装教程
微信小程序开发学习
海量号码需要保存,如何才能尽可能少地占用内存?
ClickHouse data insert, update and delete operations SQL
Introduction to Oracle Patch System and Opatch Tool
[Mysql] DATEDIFF function
机器学习—梯度下降Gradient Descent Optimization—c语言实现
[GLib] What is GType
asyncawait和promise的区别
What is SOA (Service Oriented Architecture)?
cnpm installation steps
微积分 / 自动求导
Navicat new database
np.where()用法
flask的笔记
MySQL-Explain详解
How is crawler data collected and organized?