Why difference between two pointers is not equals to size of type?

ε祈祈猫儿з 提交于 2020-01-24 01:18:08

问题


I have the simple program:

#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;
}

It produces the following output:

00DBF9B8 00DBF9AC ,sizeof(int)=4

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

If I modify the program like this:

#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;
}

I got correct result:

00394000 00394004 ,sizeof(int)=4

回答1:


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;
}

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).



来源:https://stackoverflow.com/questions/44894091/why-difference-between-two-pointers-is-not-equals-to-size-of-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!