Why do these two pointer subtractions give different results?

后端 未结 4 2026
南方客
南方客 2020-12-18 01:26

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


        
相关标签:
4条回答
  • 2020-12-18 02:04

    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).
    
    0 讨论(0)
  • 2020-12-18 02:09

    The difference between two pointers is undefined if the pointers do not point to the same array, or if the pointers were typecast from pointers to an unrelated type.

    Also, the difference is not in bytes but is in the number of elements.

    In your second case the difference is 1 byte, but it is being divided by sizeof(long). Note that because this is undefined behavior, absolutely any answer here would be correct.

    0 讨论(0)
  • 2020-12-18 02:09

    Its doing integer (long) pointer arithmetic for pi1 - pi;

    If p1 were &p[4] you'll see that it prints 1 for d1 while the difference is actually 4 bytes. This is because sizeof (long) = 4 bytes.

    0 讨论(0)
  • 2020-12-18 02:25

    Reinterpreting the underlying type of a pointer does not change its address. But pointer arithmetics yields different result depending on the pointer type. So what you have described here is perfectly correct and that is what I would expect. See pointer arithmetics.

    0 讨论(0)
提交回复
热议问题