指针类型对指针做差的影响

  尊重别人的劳动成果:http://www.cnblogs.com/nightwatcher/archive/2011/03/19/1989028.html

  之前知道指针变量其实存放的就是数据在存储空间存储的地址,而地址在32位机上往往都是32位数据,感觉都是一样的,与所指向的数据的类型关系不大。所以一直觉得指针类型的唯一作用,就是提高程序可读性,防止我们滥用指针。至于指针做差的返回值应该就是地址的差值。但是最近有一次对指针进行做差的时候,无意中发现其实并没有这么简单。
源代码如下:

 1 #include<stdio.h>
 2  
 3 int main()
 4 {
 5         int *p1 = (int *)0;
 6         int *p2 = (int *)4;
 7         int result;
 8         printf("p1 = %d, p2 = %d
", (int)p1, (int)p2);
 9         result = (int)(p2 - p1);
10         printf("p2 - p1 = %d
", result);
11         result = (int)p2 - (int)p1;
12         printf("(int)p2 - (int)p1 = %d
", result);
13         result = (int)((char *)p2 - (char *)p1);
14         printf("(char *)p2 - (char *)p1 = %d
", result);
15         return 0;
16 }

运行结果:
[root@localhost test]# ./typetest
p1 = 0, p2 = 4
p2 - p1 = 1
(int)p2 - (int)p1 = 4
(char *)p2 - (char *)p1 = 4
对比int指针类型和char指针类型的运算结果,前者得出的是1,而后者得出的是4。

  很明显可以看出,当对指针直接进行做差的时候,返回的结果其实是:地址差/sizeof(类型)。而不是简单的地址差。

 至于在c++中,实验如下·····

1     int *p1 = new int();
2     int *p2 = new int();
3     int result;
4     result = p2 - p1;
5     cout<<p1<<endl;
6     cout<<p2<<endl;
7     cout<<result<<endl;

结果是
00395440
00395470
12
两个指针差值是0X30,刚好就是48,也就是12*sizeof(int)。
至于为什么两地址差值这么大,我猜可能是WINDOWS在堆上分配内存的时候,有个最小的偏移量吧。

原文地址:https://www.cnblogs.com/kalo1111/p/3277450.html