Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does int* ip = (int *)p mean?

#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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 if ip as an int, but it is a pointer, which often has the size 8. It will therefore likely cause undefined behavior.

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

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

    printf("%p\n", (void*) ip);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading