0
#include <stdio.h>

int main(){
    char p[5] = "ABCD"; 
    int* ip = (int *)p;
    printf("%d \n", *(ip + 0)); // 1145258561 
    printf("%d \n", ip); // 6422016
}

Could anybody please explain to me the output of this program?

MinhChi
  • 25
  • 3
  • it's a cast, and that cast actually invokes undefined behavior. Please read a book first. [What does `(int*) &var` mean?](https://stackoverflow.com/q/28522618/995714), [`int num = *(int *)number;` What does this do?](https://stackoverflow.com/q/4170249/995714), [Is typecasting a `char*` to `int*` undefined?](https://stackoverflow.com/q/45303282/995714) – phuclv Jun 26 '22 at 16:11
  • 1
    casting from `char*` to `int*` is prohibited, but the reverse (`int*` -> `char*`) is allowed though: [What happens when you cast an integer array into a char array](https://stackoverflow.com/q/32539591/995714) – phuclv Jun 26 '22 at 16:15
  • 1
    @Dmitry [It ***is*** undefined behavior in this code. Full stop.](https://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule) The ***only*** safe way to convert a `char *` pointer to an `int *` pointer is if the value started as an `int *` pointer in the first place., – Andrew Henle Jun 26 '22 at 20:50

1 Answers1

8

Here you cast the char[4], p, into an int* and initialize ip with the result:

    int* ip = (int *)p;

Here you dereference ip, which, since it's an int* means that it will read sizeof(int) bytes to form an int from the address ip points at:

    printf("%d \n", *(ip + 0)); // 1145258561 

Since ints are often 4 bytes, it will often seem to work, but it violates the strict aliasing rule and results in undefined behavior. Also, if an int is 8 bytes, the program would have undefined behavior since it would then read outside the char[4].

Here you print the value of ip as an int, but it is a pointer, so again, the program will have undefined behavior. Also, a pointer is often 8 bytes so it will likely cause undefined behavior for that reason too.

    printf("%d \n", ip); // 6422016

To properly print pointers, use %p and cast the pointer to void*:

    printf("%p\n", (void*) ip);
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108