Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Consider the following code:

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 :(

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
276 views
Welcome To Ask or Share your Answers For Others

1 Answer

As others have pointed, this is undefined behavior. However, there is a very simple explanation for what you are seeing.

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

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...