指针减法混淆 [英] Pointer subtraction confusion

查看:27
本文介绍了指针减法混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们从另一个指针中减去一个指针时,差异不等于它们分开的字节数,而是等于它们分开的整数数(如果指向整数).为什么会这样?

When we subtract a pointer from another pointer the difference is not equal to how many bytes they are apart but equal to how many integers (if pointing to integers) they are apart. Why so?

推荐答案

这个想法是你指向内存块

The idea is that you're pointing to blocks of memory

+----+----+----+----+----+----+
| 06 | 07 | 08 | 09 | 10 | 11 | mem
+----+----+----+----+----+----+
| 18 | 24 | 17 | 53 | -7 | 14 | data
+----+----+----+----+----+----+

如果你有 int* p = &(array[5]) 那么 *p 将是 14.去 p=p-3code> 将使 *p 为 17.

If you have int* p = &(array[5]) then *p will be 14. Going p=p-3 would make *p be 17.

所以如果你有 int* p = &(array[5])int *q = &(array[3]),那么 pq 应该是 2,因为指针指向相隔 2 个块的内存.

So if you have int* p = &(array[5]) and int *q = &(array[3]), then p-q should be 2, because the pointers are point to memory that are 2 blocks apart.

在处理原始内存(数组、列表、映射等)时,绘制大量的框!真的很有帮助!

When dealing with raw memory (arrays, lists, maps, etc) draw lots of boxes! It really helps!

这篇关于指针减法混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆