当前位置:网站首页>C语言中变量在内存中的保存与访问
C语言中变量在内存中的保存与访问
2022-08-02 20:08:00 【Code Writers】
CPU通过内存地址访问元素
int i=0x12345678
假如i的地址是0x100,那么在小端存储体系中
地址 数值
0x100 0x78
0x101 0x56
0x102 0x34
0x103 0x12
CPU访问内存需要同时具备两个因素:
内存基址:从哪里访问内存——就是地址
内存布局:访问几个字节(怎样解析,解释方法)
定义变量时指明的数据类型就是指明内存布局,i是int型变量,所以CPU知道连同0x100后面四个地址一起组成i的值
强制类型转换改变的就是解析方法,也就是内存布局
char p= (char)i
这样CPU会只将地址0x100中的0x78解析为一个char类型的字符然后赋给p
同理 short p=(short)i
得到的short型变量p的值是0x5678
这样看来,只要给定了内存基址和内存布局就可以不用实际变量名得到变量值
比如 *(short *)0x102实际上就是值0x1234
对于结构体变量来说也是如此解析的(虽然其中有内存对齐问题)
struct foo{
int first;
short second;
char third;
}*pfoo;
对于语句 pfoo->first中的->操作符,它首先算出右侧的变量在左侧结构体中的偏移量,然后让左侧变量的地址(指针所指地址)加上偏移量就实际上得到了右侧变量的内存基址,然后根据右侧变量类型,也就是得到了它的内存布局,这样两个因素都具备了也就得到了它的值
在一些实际应用中,会看到这样的链表应用方法:将链表嵌入到数据结构中(学校里用的链表大概都是将数据结构嵌入链表)
struct data_in_list{ //数据嵌入双向链表
int price;
… //一些可能要用的数据
struct data_in_list *next;
struct data_in_list *pre;
}
//下面是链表嵌入数据结构中
struct list{
struct list *next;
struct list *pre;
}
struct list_in_data{
…//一些会用到的数据
struct list lnode;
}
比如在2.6版本的Linux内核中,这种数据结构是很常见的,进程描述符task_struct结构体中就包含链表节点,所有进程描述符是用一个双向链表连起来的,而根据链表节点访问结构体就是用到了上面说的CPU访问数据的两个要素
type 是结构体类型
address 是结构体中链表节点
field 是链表节点类型
(type*)(address - &(((type*)0)->field)) //(type*)0表示内存基址是0的type型变量,&符获得了field在type中的偏移量
//这样可以根据链表节点得到其所在的type结构体的地址,实际上可以根据结构体中任一变量得到整个结
边栏推荐
- The time series database has been developed for 5 years. What problem does it need to solve?
- ABAP grammar small review
- 【数据分析】:什么是数据分析?
- The so-called fighting skill again gao also afraid of the chopper - partition, depots, table, and the merits of the distributed
- Which thread pool does Async use?
- 「每周译Go」这次我们来点不一样的!--《How to Code in Go》系列上线
- C# Barrier class
- J9 digital theory: the Internet across chain bridge has what effect?
- PyTorch分布式backends
- EasyExcel实现动态列解析和存表
猜你喜欢
程序员也许都缺一个“二舅”精神
对话亚洲高校首个博士论文奖-裘捷中丨KDD2022
供电系统电气图
iframe------------frame-
callback prototype __proto__
Digital twins help visualize the construction of smart cities
Translate My Wonderful | July Moli Translation Program Winners Announced
牛客题目——滑动窗口的最大值、矩阵最长递增路径、顺时针旋转矩阵、接雨水问题
顺序查找和折半查找,看这篇就够了
接口测试常用工具及测试方法(入门篇)
随机推荐
Common tools and test methods for interface testing (Introduction)
Shell: conditional statements
Golang source code analysis: time/rate
Geoserver+mysql+openlayers2
如何解决图像分类中的类别不均衡问题?不妨试试分开学习表征和分类器
Redis cluster configuration
【 LeetCode 】 1374. Generate each character string is an odd number
Informatics Olympiad All-in-One (1260: [Example 9.4] Intercepting Missiles (Noip1999))
C# Monitor类
笑话:如果你在河边等待得足够久,你会看到你的敌人的尸体漂过,是怎么翻译出来的?
Parse the commonly used methods in the List interface that are overridden by subclasses
基于 outline 实现头像剪裁以及预览
LeetCode 622 设计循环队列[数组 队列] HERODING的LeetCode之路
ImageNet下载及处理
Fiddle设置接口数据用指定工具查看;Sublime Text设置json数据格式化转换
Tencent YunMeng every jie: I experienced by cloud native authors efficiency best practices case
The time series database has been developed for 5 years. What problem does it need to solve?
用了TCP协议,就一定不会丢包吗?
信息学奥赛一本通(1256:献给阿尔吉侬的花束)
Helm基础知识