当前位置:网站首页>指针的底层机制
指针的底层机制
2022-07-23 02:49:00 【小鸡岛~】
提出问题:
- 为什么指针要有类型?
C++代码
int gi;
int* p;
int main()
{
p = &gi;
*p = 12;
}
汇编
mov dword ptr ds:[006A02ECh],6A02E8h
mov eax,dword ptr ds:[006A02ECh]
mov dword ptr [eax],0Ch
机器码
C7 05 EC 02 6A 00 E8 02 6A 00
A1 EC 02 6A 00
C7 00 0C 00 00 00
发现问题的答案:
- 指针的类型信息决定了赋值/读取时写/读多少个字节;
结论:
> C语言的指针类型包含两个方面的信息:
1.地址,存放在指针变量中;
2.类型信息,关于读写的长度,没有存储在指针变量中,放在了该指针读写时的mov指令中,不同的读写长度对应的mov指令不同;
提出问题:
- 为什么类型不同的指针变量赋值编译会报错?答:编译器为了帮助程序员避免越界错误,便促产生了编译错误
- 为什么强制转换后就可以赋值?强制转换到底发生了什么?
C++代码
int i;
int* pI;
short* pS;
char* pC;
int main()
{
pI = &i;
pS = (short*)pI;
pC = (char*)pI;
*pI = 0x12345678;
*pS = 0x1234;
*pC = 0x12;
}
汇编
mov dword ptr ds:[00360610h],36060Ch
mov eax,dword ptr ds:[00360610h]
mov dword ptr ds:[00360614h],eax
mov eax,dword ptr ds:[00360610h]
mov dword ptr ds:[00360618h],eax
mov eax,dword ptr ds:[00360610h]
mov dword ptr [eax],12345678h
mov eax,1234h
mov ecx,dword ptr ds:[00360614h]
mov word ptr [ecx],ax
mov eax,dword ptr ds:[00360618h]
mov byte ptr [eax],12h
机器码
C7 05 10 06 36 00 0C 06 36 00
A1 10 06 36 00
A3 14 06 36 00
A1 10 06 36 00
A3 18 06 36 00
A1 10 06 36 00
C7 00 78 56 34 12
B8 34 12 00 00
8B 0D 14 06 36 00
66 89 01
A1 18 06 36 00
C6 00 12
问题的答案:
- 指针强制转换后的影响不是在转换的时候发生,而是在用转换后的身份去访问内存时体现到了指令中
你真的掌握了吗?
int* pI;
short sI = 12;
pI = (int*)&sI;
print("%d, %x,",*pI, *pI);
边栏推荐
- How can a platform enterprise solve the business of ledger accounting?
- IDM最新版软件的安装下载和使用方法
- 十年磨一剑,云原生分布式数据库PolarDB-X的核心技术演化
- 实现多层级条件查询(类似京东多层级添加查询)
- PHP converts ASCII code to string, and string converts ASCII code
- Matplotlib保存图片到文件
- 实现方法pathListToMap,能够将输入的pathList转化为具有层级结构的map类型
- Use recursive string inversion and Full Permutation
- 【Node中间层实践小记(一)】----搭建项目框架
- 海通证券场内基金开户怎么样安全吗
猜你喜欢
随机推荐
Teach you how to set up Alibaba cloud DDNS in Qunhui
【Node中间层实践(三)】----模板引擎pug
D template error with different types
Multi-UA V Cooperative Exploringfor the Unknown Indoor EnvironmentBased on Dynamic Target Tracking翻译
分库分表真的适合你的系统吗?聊聊分库分表和NewSQL如何选择
权限系统就该这么设计,yyds
Sentry的安装、配置、使用
数据库范式与模式分解
d类型不同的模板错误
Interviewer: explain the core principle of ThreadLocal
技术分享 | 大事务阻塞 show master status
卡特兰数---
Visual full link log tracking
spark中saveAsTextFile如何最终生成一个文件
C语言力扣第39题之组合总和。回溯法与遍历法
three文档使用
WordPress网站SEO完整教程
并发编程中volatile面试总结
软件质量管理实践全面总结
PNA modified polypeptide BZ Val Gly Arg PNA | BOC Val Leu Gly Arg PNA









