I'm hoping this isn't a duplicate question, but I've searched in some detail and haven't found my exact case before.
I have a simple struct that I also want to be able to access as a simple byte array
union
{
struct
{
unsigned char a;
unsigned char b;
// ... Some other members ...
unsigned char w;
};
unsigned char bytes[sizeof( what? )];
} myUnion;
Notice the struct is not named and it also isn't given its own member name. This is so that I can use myUnion.a
to access that member, and not myUnion.myStruct.a
.
However, without some name, how can I get the size of the struct for myUnion.bytes[]
other than manually calculating it each time I change something?
My current workaround is to use a #define
to make up for the myUnion.myStruct
problem, but that has the negative side-effect of ruining my auto-complete in the editor, and also makes my data structures harder to understand.
Any ideas?
Note: This is running on an 8-bit processor. There are no issues with word alignment and such. That said, any caveats should probably be stated so someone else doesn't use a proposed solution inappropriately.
bytes
via a cast or a function call. The fewer non-standard constructs and hacks you use, the fewer headaches you will have down the track – Cardamom