Why do these two pointer subtractions give different results?

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

提交回复
热议问题