Subtracting two pointers giving unexpected result

后端 未结 6 1245
灰色年华
灰色年华 2021-01-26 14:56
#include 

int main() {
    int *p = 100;
    int *q = 92;
    printf(\"%d\\n\", p - q);  //prints 2
}

Shouldn\'t the output of above pr

6条回答
  •  Happy的楠姐
    2021-01-26 15:22

    These are integer pointers, sizeof(int) is 4. Pointer arithmetic is done in units of the size of the thing pointed to. Therefore the "raw" difference in bytes is divided by 4. Also, the result is a ptrdiff_t so %d is unlikely to cut it.

    But please note, what you are doing is technically undefined behaviour as Sourav points out. It works in the most common environments almost by accident. However, if p and q point into the same array, the behaviour is defined.

    int a[100];
    int *p = a + 23;
    int *q = a + 25;
    
    printf("0x%" PRIXPTR "\n", (uintptr_t)a); // some number
    printf("0x%" PRIXPTR "\n", (uintptr_t)p); // some number + 92
    printf("0x%" PRIXPTR "\n", (uintptr_t)q); // some number + 100
    printf("%ld\n", q - p); // 2
    

提交回复
热议问题