-1

I am trying to write 512 bytes as unsigned char, but read them as fields in a struct. Below is the union I have come up with.

typedef union {
    unsigned char buffer[512]; //512 bytes
    struct {
            unsigned char a[446];
            struct part b[4]; //sizeof(part) = 16
            unsigned char c[2];
    }parsed; //446 + 4*16 + 2 = 512 bytes
}tbl;

I can write into buffer properly, but reading from a or b or c give 0. - I am using gcc - on a 64 bit Linux machine - No difference with/without -m32 flag.

Can someone please throw some light what I'm missing?

timrau
  • 22,578
  • 4
  • 51
  • 64
stackoverflow
  • 399
  • 2
  • 14

2 Answers2

1

You really shouldn't do this. most likely, your structure is larger than 512 bytes, because of alignment issues. or, to put it differently, the compiler puts empty space between the struct fields.

if you want to avoid that for a performance penalty, have a look at the #pragma pack directive. Maybe it's supported by your compiler.

EDIT: also, please show how you write to buf. if a is 0 as well, you may have an error there.

Andreas Grapentin
  • 5,499
  • 4
  • 39
  • 57
0

Oops, sorry. It works perfectly fine. Apparently, b[1] was all zeros.. and I was comparing it against b[0] fields. Apologies.

stackoverflow
  • 399
  • 2
  • 14
  • Please consider anyway the information about padding in the answer of @AndreasGrapentin . This because the code as you posted ist is not portable (not even guaranteed between different compilers) and can lead to serious "hidden" problems. – junix Feb 23 '13 at 08:21
  • Yes, Andreas is right. I forgot to mention that my struct 'part' is already packed. – stackoverflow Feb 23 '13 at 22:25