0

I have a problem in C in Keil which is below this is sample C code.

struct A
{
    uint8_t header;
    uint16_t volume;
    uint16_t temp;
    uint8_t footer;
};


union {
    struct A Packet;
    uint8_t buff[6];
} A_union;

The problem is I want to fill struct with a header,footer and data and serialize it with buff but union changes byte offset (I cant even see footer in buff)as you can see in the picture. how can I solve it?

Update: as Sander suggested in this link I solved the problem by modifying struct as below

    struct __attribute__((__packed__)) A{
...}

 this is image filled each byte with distinctive value for each byte

david
  • 465
  • 5
  • 11
  • 1
    By making the `struct` a **packed** `struct`. I feel sure that nothing changes the `struct` you are using and it will have the same size in both uses. – Weather Vane Feb 26 '19 at 14:18
  • 1
    you might also want to read up on [structure padding](https://stackoverflow.com/questions/4306186/structure-padding-and-packing) – Sander De Dycker Feb 26 '19 at 14:18
  • 1
    Because padding. You have to use Keil's compiler-specific non-standard way of packing a struct (if your hardware can handle such). If you want to serialize/de-serialize a struct portably, there's actually no other way than manually writing/reading each member in run-time. – Lundin Feb 26 '19 at 14:20
  • @SanderDeDycker The reason that I did not find the page you suggested is that I did not know anything about "Packing" and "Padding". may be this question be helpful for others like me. anyway thanks for your help – david Feb 26 '19 at 15:18
  • @Lundin: Keil's way has the advantage that treating packed-ness as a qualifier allows it to apply to pointers. The address of a member of a `__packed`-qualified structure will be a `__packed` qualified pointer, which may be used to access the member (even if it's not aligned) but cannot be assigned to a non-`packed` pointer . – supercat Feb 27 '19 at 01:03
  • @david : that's ok. Your question still exists, and is still searchable by others, so it can still be helpful. A question is marked as duplicate, when we believe there is already a good answer in the database, and there's no reason to answer it again (in fact, ideally, every question should have 1 canonical answer, to avoid having to wade through dozens of answers to find the one you need). If your question was not answered by the duplicate, you can edit and re-open your question. More details : [Why are some questions marked as duplicate?](https://stackoverflow.com/help/duplicates). – Sander De Dycker Feb 27 '19 at 07:31

0 Answers0