Subtracting two pointers giving unexpected result

后端 未结 6 1194
灰色年华
灰色年华 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条回答
  •  清酒与你
    2021-01-26 15:27

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

    It is called pointer arthmetic what happens there.

    The value will be (100-92)/sizeof(int). In your case sizeof(int)=4.

    In ISO9899 pointer arithmetic is defined so for subtraction ptr-ptr. Chapter 6.5.6p9

    When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.

提交回复
热议问题