R
Ravishankar S
Hello C experts,
I have a doubt regarding the layout of structs in C. Is it guranteed by the
standard that the members of a struct are laid in order declared ?
If i remember correct, then compiler may reorder the members if it saves
memory (or runtime..?). But i also remember something like this:
struct {
char var1;
int var2
short int var3;
} s1;
&s1 == &s1.var1 /* This is guranteed , im sure..*/ But..
&s1.var1 < &s1.var2 < s1.var3 /* This may not be guranteed */
My application:
I have tow structs, one having all uint8 members and another having uint32
members. I want to take the address of the struct and use it as an array in
code..
struct {
uint8 var1;
uint8 var2;
uint8 var3;
} s2;
uint8 *array1 = (uint8*) & s2;
array1[0] == s1.var1 , array1[1] == s1.var2 /* and so on */
Similarly for the other struct having uint32 members.
My guess is that since the members are all of the same type (and size), the
compiler will not do rearrangement..
Your comments welcome..
Kind Regards,
Ravishankar
I have a doubt regarding the layout of structs in C. Is it guranteed by the
standard that the members of a struct are laid in order declared ?
If i remember correct, then compiler may reorder the members if it saves
memory (or runtime..?). But i also remember something like this:
struct {
char var1;
int var2
short int var3;
} s1;
&s1 == &s1.var1 /* This is guranteed , im sure..*/ But..
&s1.var1 < &s1.var2 < s1.var3 /* This may not be guranteed */
My application:
I have tow structs, one having all uint8 members and another having uint32
members. I want to take the address of the struct and use it as an array in
code..
struct {
uint8 var1;
uint8 var2;
uint8 var3;
} s2;
uint8 *array1 = (uint8*) & s2;
array1[0] == s1.var1 , array1[1] == s1.var2 /* and so on */
Similarly for the other struct having uint32 members.
My guess is that since the members are all of the same type (and size), the
compiler will not do rearrangement..
Your comments welcome..
Kind Regards,
Ravishankar