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

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

#include<stdio.h>

int main()
{
        int *p1 = (int *)0;
        int *p2 = (int *)4;
        int result;
        printf("p1 = %d, p2 = %d\n", (int)p1, (int)p2);
        result = (int)(p2 - p1);
        printf("p2 - p1 = %d\n", result);
        result = (int)p2 - (int)p1;
        printf("(int)p2 - (int)p1 = %d\n", result);
        result = (int)((char *)p2 - (char *)p1);
        printf("(char *)p2 - (char *)p1 = %d\n", result);
        return 0;
}

运行结果:
[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(类型)。而不是简单的地址差。

posted on 2011-03-19 20:11  守夜者  阅读(1143)  评论(6编辑  收藏  举报

导航