为什么这两个指针减法给不同的结果? [英] Why do these two pointer subtractions give different results?

查看:111
本文介绍了为什么这两个指针减法给不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

char* p = new char[2];
long* pi = (long*) p;
assert(p == pi);         // OK

char* p1 = &p[1];
long* pi1 = (long*) p1;
assert(p1 == pi1);       // OK

int d = p1 - p;
int d1 = pi1 - pi;
assert(d == d1);         // No :(

运行后,我得到 d == 1 和 d1 == 0 ,但 p1 == pi1 > p == pi (我在调试器中检查过)。这是未定义的行为吗?

After this runs, I get d == 1 and d1 == 0, although p1 == pi1 and p == pi (I checked this in the debugger). Is this undefined behavior?

推荐答案

指针之间的区别是元素的数量,不是它们之间的字节数。

The difference between pointers is the number of elements, not the number of bytes between them.

pi和pi1都指向long,但是pi1指向的地址比pi只是一个字节,假设longs是4字节长,地址的差异,1除以元素的大小,4,是0.

pi and pi1 both point to longs, but the address pointed to by pi1 is only one byte further than pi. Presuming longs are 4 bytes long, the difference in the addresses, 1, divided by the size of the element, 4, is 0.

另一种思考方式是,你可以想象编译器将生成与此相等的代码以计算d1:

Another way of thinking of this is you could imagine the compiler would generate code equivalent to this for calculating d1:

int d1 = ((BYTE*)pi1 - (BYTE*)pi)/sizeof(long).

这篇关于为什么这两个指针减法给不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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