I want to split a big type thing into several little type things. For example, change a uint32_t variable to four char things. Below is my method:
uint32_t big = 0x01234567; // little endian
char* ptr = (char*)&big + 1; // points to 0x45
*(ptr+1) = 0xff;
printf("%08x", big); //01ff4567
Is that a defined behavior? Or is there more proper way? On the contrary, I know that
int a = 20, b = 30, c = 40;
int* d = &b;
*(d+1)=60; // some compiler will pass; while some will error
for(int i=0;i<5;i++)
printf("%d, ",*(d+i));
is an undefined behavior, because we access the memory outside the scope of where the pointer points to. If the first case is legal, then I wonder what is the difference? Is that to say, if the program safely owns the whole region, like
- declaring a big type variable
uint32_t big = 0x01234567and do the things above, or - like declaring an array (so we sure there are consecutive memory owned by us), for example,
int apple[4] = {10,20,30,40}; int* ptr = &apple[1]; *(ptr + 1) = 666; // success to move or edit the value, // even originally ptr is only an int type pointer for (int k = 0; k < 15; k++) { printf("%d\n", *(ptr + k)); }
Then accessing the memory outside the original scope of the type that the pointer declared is legal? This is quite confusing.