C question with pointers

后端 未结 4 1560
慢半拍i
慢半拍i 2021-01-27 20:40

I have a program question, here is the code.

int main()
{
int *p,*q;
p=(int*)1000;
printf(\"%d \",p);
q=(int*)2000;
printf(\"%d\",q);
printf(\"%d\",(p-q));
retu         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-27 21:20

    When you subtract two pointers, as long as they point into the same array, the result is the number of elements separating them.

    On your platform, an int is 4 bytes. There are -250 elements between address 2000 and address 1000.

    Since p and q don't both point to the same array, the result is undefined. You could get any result, including the one you expect.

提交回复
热议问题