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.

4
  • 2
    First, buckle up by checking and understanding the strict aliasing rule stackoverflow.com/questions/98650/… . Then, you may have a look at unions. And then, try and make yourself comfortable with structure member alignment in your compiler and probably the term packed structures. Commented Mar 11, 2016 at 7: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. Commented Mar 11, 2016 at 7:57
  • Unionise them with a 4-bit var. Commented Mar 11, 2016 at 8: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; Commented Mar 11, 2016 at 9:55

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

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 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.