指针减法混乱 [英] Pointer subtraction confusion
问题描述
当我们减去从另一个指针的差值不等于它们相距多少字节,但等于一个指针(如果指向整数)多少整数它们分开。为什么会这样?
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 =及(数组[5])
然后 * P
将是14 。展望 p = p-3
将使 * 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 =及(数组[5])
和为int * Q =及(阵列[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屋!