简体   繁体   中英

Why is (int)((int *)0 + 4) == 16?

I have tested this, k is 16, but why?

int main(int argc, char **argv) {
    int k = (int)((int *)0 + 4);
    printf("%d", k);

    return 0;
}

Important note: Pointer arithmetic on a pointer that does not point to an array is undefined behavior. You can get 16, but you can also get a crash, for example, if the implementation chooses to produce a trap representation for the result.

This is pointer arithmetic: when you add a number x to a pointer to T , numeric value that corresponds to the pointer is increased by x * sizeof(T) .

In your case, the numeric value of the pointer is zero, x is 4, and sizeof(int) is also 4. 4*4 yields 16.

Pointer arithmetic in C use the type's size as an unit; adding 1 to int* will make it advance by 4 (assuming int is 32bit).

EDIT: pointer arithmetic on invalid pointers (including NULL) is 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