I've got a question regarding the behavior of structs in C.
Take the given structs as an example:
typedef struct {
char num1;
char num2;
} structa;
typedef struct {
structa innerstruct;
char num3;
char num4;
} structb;
I assume since structb contains a structa field, rather than a pointer to one, that structb would be laid out in memory as such:
struct {
char num1; //innerstruct num1
char num2; //innerstruct num2
char num3; //num3
char num4; //num4
};
If so, can you access each field like this?
*(((char *)&structbvar) + 0) = 1; //innerstruct num1
*(((char *)&structbvar) + 1) = 2; //innerstruct num2
*(((char *)&structbvar) + 2) = 3; //num3
*(((char *)&structbvar) + 3) = 4; //num4
or access them like this?
((structa)structbvar).num1 = 1; //innerstruct num1
((structa)structbvar).num2 = 2; //innerstruct num2
Regardless of if that's bad practice or not.
Also is it reliable/portable?
Edit, as pointed out by Matt McNabb you can't directly cast structs so it should be:
((structa *)&structbvar)->num1 = 1; //innerstruct num1
((structa *)&structbvar)->num2 = 2; //innerstruct num2