Subtracting two pointers giving unexpected result

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

    This

    int *p = 100;
    int *q = 92;
    

    is already invalid C. In C you cannot initialize pointers with arbitrary integer values. There's no implicit integer-to-pointer conversion in the language, aside from conversion from null-pointer constant 0. If you need to force a specific integer value into a pointer for some reason, you have to use an explicit cast (e.g. int *p = (int *) 100;).

    Even if your code somehow compiles, its behavior in not defined by C language, which means that there's no "should be" answer here.

提交回复
热议问题