C: long pointer pointing to address with an integer

时间:2018-03-25 19:21:05

标签: c pointers printf

Why does the first printf() output 1 and the second one 8589934593? EDIT: Why does the second one output exactly 8589934593 and not some other number?

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]){
    int *intPtr = NULL;
    long *longPtr = NULL;

    int array[5] = {0,1,2,3,4};
    intPtr = &array[1];
    longPtr = &array[1];
    printf("%d\n", *intPtr);
    printf("%ld\n", *longPtr);
}

1 个答案:

答案 0 :(得分:2)

Because it's undefined behavior. Pointing a long* to the address of an int and acting like it's a long violates the strict aliasing rule, giving you undefined behavior.