C question with pointers

后端 未结 4 1559
慢半拍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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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); 
    }
    
    0 讨论(0)
  • 2021-01-27 21:39

    So much undefined behaviour in this program, the values printed are really quite immaterial.

    0 讨论(0)
提交回复
热议问题