#include<stdio.h>
#include<stdlib.h>
static char mem[4];
int main()
{
int* A = (int*)(mem);
mem[0] = 0;
mem[1] = 1;
mem[2] = 2;
mem[3] = 3;
int i;
A[0] = 5;
for (i = 0; i<4; i++)
{
printf("%d\t", mem[i]);
}
printf("\n");
return 0;
}
My question is, why does this print 5 0 0 0 rather than 5 1 2 3? Why is the array "wiped out?"
char
andint
don't have the same sizes. writing the first element ofA
writes all 4 elements ofmem
A[0] = 123456789;
to make it more intuitively understandable.int* A = (int*)(mem);
--> risks undefined behavior per "If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined." C11dr §6.3.2.3 7