0

How to access entire structure members in C.Means I want to take all the data of variables in structure.

struct data
{
char a:1;
char b:2;
char c:3;
char d:1;
} arr;

I can access individual members by using . operator.But i need to access all members in that structure.Colud you please tell me how to do.

jotik
  • 17,044
  • 13
  • 58
  • 123
  • 2
    First, buckle up by checking and understanding the *strict aliasing rule* http://stackoverflow.com/questions/98650/what-is-the-strict-aliasing-rule . Then, you may have a look at *union*s. And then, try and make yourself comfortable with *structure member alignment* in your compiler and probably the term *packed* structures. – tofro Mar 11 '16 at 07:21
  • 2
    You should avoid bit fields in the first place, they are unsafe and non-portable. Use bit masks and bit-wise operators instead. – Lundin Mar 11 '16 at 07:57
  • Unionise them with a 4-bit var. – Martin James Mar 11 '16 at 08:02
  • Why don't you just use the `arr` variable directly and trust the compiler to do its own optimizations? E.g. `struct data arr2 = arr;` – jotik Mar 11 '16 at 09:55

1 Answers1

2

As suggested make an union of the whole data and of the bitfield structure.

union
{
    char Whole;
    struct data
    {
        char a:1;
        char b:2;
        char c:3;
        char d:1;
    } arr;
} MyData;
Frankie_C
  • 4,764
  • 1
  • 13
  • 30
  • To begin with, using `char` for bit-fields is not covered by the C standard, it is a non-standard language extension. Then there is the bit order and alignment - poorly specified. Then there is potential padding bits and bytes - poorly specified. And then, unrelated to the bit-field itself, the char type has poorly specified signedness. What happens when you use a signed type for bit-fields is not specified. And so on. So I don't think it is possible for anyone to predict what this union will do. In might work, it might crash and burn, it might cause latent bugs. Have fun using bit-fields! – Lundin Mar 11 '16 at 09:16
  • @Lundin I fully agree. You forgot to add also that the fields layout, compiler implementation dependent, are dependent also from processor endianess. They were introduced as an help for low level and kernel programming, typically to access hardware register bits in memory mapped I/O. For this reason they have to be considered machine/processor specific and aren't portable. – Frankie_C Mar 11 '16 at 09:48