C question with pointers

后端 未结 4 1562
慢半拍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条回答
  •  -上瘾入骨i
    2021-01-27 21:22

    p is a pointer variable, which can store only address of a int variable. But you are storing 1000 as an address, which is invalid. And then you are storing 2000 to the variable q.

    Now you are doing pointer arithmatic p-q. Always pointer arithmatic will gives the output based on the size of the type of address. Which will work like (p - q)/sizeof(type).

    Consider if p and q are char * variable, then p-q will gives you the output as -1000

    In your case p and q are int * variable, then p-q will gives you the output as 250 if size of int is 4 bytes. Execute this on the compiler where size of int is 2 bytes, you will get a result as -500.

提交回复
热议问题