cancel
Showing results for 
Search instead for 
Did you mean: 

Struct in union

ramesh130
Associate II
Posted on September 20, 2010 at 06:17

Struct in union

6 REPLIES 6
Posted on May 17, 2011 at 14:07

''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 is

not

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...
ashley23
Associate II
Posted on May 17, 2011 at 14:07

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?

daviddavid92
Associate II
Posted on May 17, 2011 at 14:07

add __attribute__((__packed__)) to your struct definition.

Assuming you are using GCC.

Chris.

Posted on May 17, 2011 at 14:07

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!

ramesh130
Associate II
Posted on May 17, 2011 at 14:07

I am using KEIL compiler.

ramesh130
Associate II
Posted on May 17, 2011 at 14:07

I am new to microcontroller programming. Can you please suggest what is the best way of declaring this so that it becomes portable??