+ 3
void pointer and different type value
in this code I try test return different type declared variable, but wonderful things in out put : char c = 'a'; ptr = &c; printf("void ptr points to %c", *((int *)ptr)); is -> 'a' and for int x = 33; printf("void ptr points to %d\n", *((char *)ptr)); is -> 33 why? https://code.sololearn.com/cIkHV9MrHM7N/?ref=app
1 Respuesta
+ 8
To extend swim's wonderful explanation,
Remember that different types are the representation of containers of different sizes. An int is 4 bytes. A char is 1 byte. What happens when you do
int x = 33;
char* ptr = &x;
is that the pointer points to the first byte of x and tries to treat it as a char. Whatever wonderful things that would happen later is dependent on the compiler implementation. This leads to our best friend, undefined behaviour.