#include <stdio.h>
int main() {
double p = 10.3;
void *j = &p;
*((int*) j) = 2;
printf("%i: %p\n", *((int *)j), &p);
printf("%i: %p\n", (int)p, &p);
return 0;
}
So apparently, I think this is what happens, and I am sure I am not right:
Assume that a double is 8 bytes and an int is 4 bytes.
When I cast j
to int*
and assign it the value 2
via pointer dereference, the left hand side of the assignment basically assigns the first four bytes of j the value 2
.
Now in the first printf
statement, it works as expected, the first four bytes equal the value 2
. But in the second printf
statement, when I cast p
to int, why is it not printing 2
? Didn't I overwrite the first four bytes of p via the void pointer and assigned to them the value 2
?
So what exactly is happening here? And what is the proper framework required to understand it correctly?