2010-09-19 09:17 PM
Struct in union
2011-05-17 05:07 AM
''What could be going wrong here?''
Nothing is actually ''wrong'' - this kind of behaviour is entirely to be expected! The fundamental issue with this technique is that it isnot
portable - is it completely and entirely reliant upon the specific implementation details of the particular compiler used! As already noted, the specific implementation details most likely to be involved are data alignment, padding, data sizes, and byte ordering. You might be able to get this to work by re-defining the union - or it might be better to just start from scratch...2011-05-17 05:07 AM
Could be something to do with the alignment of data in your struct. Maybe it is aligned on 32 bit boundaries. Perhaps you will need to specify that it be packed to 8 bit boundaries?
Try loading test data eg a,b,c,d,e,f,g into your 23 byte array then access the struct members to see how they line up with test data. Also look at the memory view in the simulator to see where things go when you write to the struct compared to where you think they should go.
What compiler are you using?
2011-05-17 05:07 AM
add __attribute__((__packed__)) to your struct definition.
Assuming you are using GCC. Chris.2011-05-17 05:07 AM
Yes, that should address the specific issue of alignment/packing - but it still leaves the other issues of data sizes, byte ordering, etc unaddressed.
Again, the basic problem is that this approach is fundamentally non-portable - so there should be no expectation that it will ''just work'' when moved to a different target and/or a different compiler! There isn't even a guarantee that it will continue to work between different versions of the same compiler!2011-05-17 05:07 AM
I am using KEIL compiler.
2011-05-17 05:07 AM
I am new to microcontroller programming. Can you please suggest what is the best way of declaring this so that it becomes portable??