简体   繁体   中英

C: long pointer pointing to address with an integer

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM