Pointer subtraction confusion

2019-01-01 07:12发布

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?

标签: c
8条回答
闭嘴吧你
2楼-- · 2019-01-01 07:29

Say you have an array of 10 integers:

int intArray[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Then you take a pointer to intArray:

int *p = intArray;

Then you increment p:

p++;

What you would expect, because p starts at intArray[0], is for the incremented value of p to be intArray[1]. That's why pointer arithmetic works like that. See the code here.

查看更多
永恒的永恒
3楼-- · 2019-01-01 07:31

This is consistent with the way pointer addition behaves. It means that p1 + (p2 - p1) == p2*.

Pointer addition (adding an integer to a pointer) behaves in a similar way: p1 + 1 gives you the address of the next item in the array, rather than the next byte in the array - which would be a fairly useless and unsafe thing to do.

C could have been designed so that pointers are added and subtracted the same way as integers, but it would have meant:

  • doing p2 = p1 + n * sizeof(*p1) instead of p2 = p1 + n
  • doing n = (p2 - p1) / sizeof(*p1) instead of n = p2 - p1

This would result in code that is longer, harder to read, and less safe.

*: assuming that the difference between p1 and p2 is an exact multiple of the type they point to. If they are in the same array of memory, this will be true. If they are not, then it doesn't much sense doing pointer arithmetic on them.

查看更多
冷夜・残月
4楼-- · 2019-01-01 07:35

So that the answer is the same even on platforms where integers are different lengths.

查看更多
浅入江南
5楼-- · 2019-01-01 07:35

@fahad Pointer arithmetic goes by the size of the datatype it points.So when ur pointer is of type int you should expect pointer arithmetic in the size of int(4 bytes).Likewise for a char pointer all operations on the pointer will be in terms of 1 byte.

查看更多
还给你的自由
6楼-- · 2019-01-01 07:38

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
+----+----+----+----+----+----+

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

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!

查看更多
千与千寻千般痛.
7楼-- · 2019-01-01 07:47

"When you subtract two pointers, as long as they point into the same array, the result is the number of elements separating them"

Check for more here.

查看更多
登录 后发表回答