C question with pointers

后端 未结 4 1561
慢半拍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:23

    Correct but probably useless answer: p - q is equal to (1000 - 2000) / (sizeof int). For most C compiles, sizeof int is 4.

    Potentially more useful answer: the effect of typecasts like (int*) 1000 is undefined. That code creates a pointer to an int at address 1000. That address is probably invalid. To create a pointer to an int with value 1000, write this:

    int i = 1000;
    int *p = &i;
    

    Now p points to i, and *p, the value pointed to by p, is 1000.

    Here is some correct code that may say what you meant:

    int main() {
      int i = 1000;
      int j = 2000;
    
      int *p = &i;
      int *q = &j;
    
      printf("i = %d *p = %d\n", i, *p);
      printf("j = %d *q = %d\n", j, *q);
      printf("*p - *q = %d\n", *p - *q); 
    }
    

提交回复
热议问题