Why do these two pointer subtractions give different results?

后端 未结 4 2036
南方客
南方客 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: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.

提交回复
热议问题