When accessing a structure from a byte stream (File, Network, etc...) what does alignment mean?
For example, I can understand why a compiler would want to pad the following structure with extra bytes to align the int a and short b at word addresses (multiples of 4). However, what does this mean when accessing memory at a random address via using a pointer? Does using the -> operator generate inefficient code? Or am I missing something?
typedef struct{
void* ptr; //4 bytes
char c1; //1 byte
int a; //4 bytes
char c2; //1 byte
short b; //2 byte
char c3; //1 byte
} Odd_Struct; //Minimum needed = 13 bytes, actual (with padding) = 20
unsigned char buffer[128];
Odd_Struct odd_struct;
odd_struct.a = 123456789;
odd_struct.b = 12345;
printf("sizeof(odd_struct): %d\n", sizeof(Odd_Struct));
memcpy(buffer+3, &odd_struct, sizeof(Odd_Struct));
Odd_Struct* testPtr = (Odd_Struct*)(buffer+3);
printf("testPtr->a: %d\n", testPtr->a);
printf("testPtr->b: %d\n", testPtr->b);
And the output
sizeof(odd_struct): 20
testPtr->a: 123456789
testPtr->b: 12345
To answer why I would want to do this:
I am intending to use a system with very limited RAM, so it's tempting to just cast a byte (unsigned char) pointer to a struct pointer and access it that way. Without an additional copy of memory. I.E. use the bytes in place. This is working fine on a x86 PC using gcc. But based on comments below, this seems like it might be a bad idea.