Subtracting two pointers giving unexpected result

后端 未结 6 1292
灰色年华
灰色年华 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:34

    Your code is undefined behavior.

    You cannot simply subtract two "arbitrary" pointers. Quoting C11, chapter §6.5.6/P9

    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. The size of the result is implementation-defined, and its type (a signed integer type) is ptrdiff_t defined in the header. [....]

    Also, as mentioned above, if you correctly subtract two pointers, the result would be of type ptrdiff_t and you should use %td to print the result.


    That being said, the initialization

     int *p = 100;
    

    looks quite wrong itself !! To clarify, it does not store a value of 100 to the memory location pointed by (question: where does it point to?) p. It attempts to sets the pointer variable itself with an integer value of 100 which seems to be a constraint violation in itself.

提交回复
热议问题