黑马程序员技术交流社区

标题: 两个指针变量相减的结果分析 [打印本页]

作者: zhudong100    时间: 2015-10-22 22:01
标题: 两个指针变量相减的结果分析
  1. #include <stdio.h>

  2. int main(int argc, const char * argv[]) {
  3.     int a[3] = {0,1,2};
  4.     printf("%p\n",&a[0]);
  5.     printf("%p\n",&a[2]);
  6.     printf("%p\n",&a[2] - &a[0]);
  7.     return 0;
  8. }
复制代码

地址是用0x(即16进制)表示,&a[2] - &a[0]的结果是8才对,为什么打印的结果是2呢?
作者: liulunjiang    时间: 2015-10-24 14:25
在C标准当中,见下文粗体。
When two pointers to members of the same array object are subtracted, the difference is divided by the size of a member. The result represents the difference of the subscripts of the two array members. The size of the result is implementation-defined, and its type (a signed integral type) is ptrdiff_t defined in the <stddef.h> header. As with any other arithmetic overflow, if the result does not fit in the space provided, the behavior is undefined. If two pointers that do not point to members of the same array object are subtracted, the behavior is undefined. However, if P points either to a member of an array object or one past the last member of an array object, and Q points to the last member of the same array object, the expression (Q+1) - P has the same value as (Q-P) + 1, even though Q+1 does not point to a member of the array object.

当同一个数组的两个成员的指针相减时,其差值为:地址值的差,再除以一个数组成员的size。这个结果代表了两个指针对应元素的下标之差。
取地址的情况也是一个道理。
作者: aidan    时间: 2015-10-24 15:22
楼上说得好
作者: zhudong100    时间: 2015-10-26 10:14
liulunjiang 发表于 2015-10-24 14:25
在C标准当中,见下文粗体。
When two pointers to members of the same array object are subtracted, the  ...

在数组当中才是这种情况,对吗?
作者: 超の    时间: 2015-10-26 11:29
liulunjiang 发表于 2015-10-24 14:25
在C标准当中,见下文粗体。
When two pointers to members of the same array object are subtracted, the  ...

学到了!
作者: amoshaxiangp    时间: 2015-10-26 15:43
学习了,果然高神
作者: knight_zfh1288    时间: 2015-10-26 19:51
英文正解
作者: yuweiyuwei    时间: 2015-10-26 21:41
虽然理解的时候想到是这样 但是并不能确定=.= 也没有像lz这样把这个问题的认真的看待
作者: liulunjiang    时间: 2015-10-27 08:15
zhudong100 发表于 2015-10-26 10:14
在数组当中才是这种情况,对吗?

貌似是的
作者: liujun_lll    时间: 2015-10-27 14:45
int a[3] = {0,1,2};
    printf("%p\n",&a[0]);
    printf("%p\n",&a[2]);
    printf("%p\n",&a[2] - &a[0]);


通俗理解 a[0]地址为a ,a[2]地址为a+2,所以&a[2] - &a[0] == a+2 -a == 2





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2