Why do these two pointer subtractions give different results?

后端 未结 4 2034
南方客
南方客 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题