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:51

When applying arithmetic operations on pointers of a specific type, you always want the resulting pointer to point to a "valid" (meaning the right step size) memory-address relative to the original starting-point. That is a very comfortable way of accessing data in memory independently from the underlying architecture.

If you want to use a different "step-size" you can always cast the pointer to the desired type:

int a = 5;
int* pointer_int = &a;
double* pointer_double = (double*)pointer_int; /* totally useless in that case, but it works */
查看更多
怪性笑人.
3楼-- · 2019-01-01 07:52

Because everything in pointer-land is about offsets. When you say:

int array[10];
array[7] = 42;

What you're actually saying in the second line is:

*( &array[0] + 7 ) = 42;

Literally translated as:

* = "what's at"
(
  & = "the address of"
  array[0] = "the first slot in array"
  plus 7
)
set that thing to 42

And if we can add 7 to make the offset point to the right place, we need to be able to have the opposite in place, otherwise we don't have symmetry in our math. If:

&array[0] + 7 == &array[7]

Then, for sanity and symmetry:

&array[7] - &array[0] == 7
查看更多
登录 后发表回答