为什么两个指针之间的差异不等于类型的大小? [英] Why difference between two pointers is not equals to size of type?

查看:57
本文介绍了为什么两个指针之间的差异不等于类型的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的程序:

#include <iostream>

using namespace std;


int main()
{
    int a = 5;
    int b = 6;
    int* p1 = &a;
    int* p2 = &b;
    std::cout << p1 << " " << p2 << " ,sizeof(int)=" << sizeof(int) << std::endl;

    system("pause");
    return 0;
}

它产生以下输出:

00DBF9B8 00DBF9AC ,sizeof(int)=4

但是,00DBF9B8 - 00DBF9AC == С.我不明白这个结果.

but, 00DBF9B8 - 00DBF9AC == С. I cannot understand this result.

如果我这样修改程序:

#include <iostream>

using namespace std;


int main()
{
    static int a = 5;
    static int b = 6;
    int* p1 = &a;
    int* p2 = &b;
    std::cout << p1 << " " << p2 << " ,sizeof(int)=" << sizeof(int) << std::endl;

    system("pause");
    return 0;
}

我得到正确的结果:

00394000 00394004 ,sizeof(int)=4

推荐答案

不能保证将局部变量(甚至静态变量)放在连续的内存地址上.实际上,如果减去两个不指向同一数组的指针值,那将是未定义的行为.

There is no guarantee that local variables (or even static variables) are put on consecutive memory addresses. And actually it would be undefined behaviour if you substracted two pointer values that do not point into the same array.

但是您可以如下使用指针算法:

But you could use pointer arithmetics as follows:

int main()
{
    int a;
    int* p1 = &a;
    int* p2 = p1+1;
    std::cout << p1 << " " << p2 << " ,sizeof(int)=" << sizeof(int) << std::endl;

    return 0;
}

请注意,单个整数值可以视为大小为1的数组,因此p1+1指向数组的最后一个元素之后的一个",因此操作p2 = p1+1实际上是有效的(解引用p2则当然无效).

Note that a single integral value may be considered as an array of size 1, and that p1+1 therefore points to "one after the last element of an array", such that the operation p2 = p1+1 is actually valid (dereferencing p2 then would not be valid, of course).

这篇关于为什么两个指针之间的差异不等于类型的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆