简体   繁体   中英

structure with bitfields, memory allocation for array

I want to use a structure as given below on my ARM Cortex M0. I am using C programming.

struct path_table_t {
    uint8_t lut_index;
    uint8_t flag : 1;
};

flag field is made to be single bit by bit fields. How will be the memory allocation for the array of above mentioned structure will happen?

Will I get the benefit of bit fields as saving in total memory?

Most likely the sizeof(struct path_table_t) == 2 . That is, structure with 2 elements, with each being 8 bits. 7 bits of flag should remain unused, but are still reserved.

Note that C standard gives a lot of room for compiler implementation to vary the size required by the bit fields. For example (N1570, 6.7.2.1 p11):

An implementation may allocate any addressable storage unit large enough to hold a bit- field.

and

The alignment of the addressable storage unit is unspecified.

So the space being reserved by the flag and its padding might be even larger.

If you wish to be sure, check the size with sizeof . Just remember that changing compiler or compiler settings might affect the result.

To answer your question
Will I get the benefit of bit fields as saving in total memory?
NO

consider two struct's

struct path_table1_t {
    uint8_t lut_index;
    uint8_t flag : 1;
}a;

and

struct path_table2_t {
    uint8_t lut_index;
    uint8_t flag;
}b;

sizeof(a) and sizeof(b) is equal .

But incase you are planning to use all the bits in the given bit field then the memory allocated is reduced. Like

struct path_table3_t {
    uint8_t lut_index : 1;
    uint8_t flag : 1;
}c;

In this case the sizeof(c) is the sizeof(uint8_t) which will be 1 byte. To summarize:
sizeof(c) < sizeof(a) and sizeof(a) = sizeof(b)

If you are very much interested to save memory then use the keyword __attribute__((__packed__)) , where this directive would make compiler to squeeze in the memory allocated for this struct upto which the user is using.

Memory allocation for bit fields is implementation defined. Let's consider your example:

struct path_table_t {
   uint8_t lut_index;
   uint8_t flag : 1;
};

int main()
{
   struct path_table_t p;

   printf("%d\n",sizeof(p));
}

Here you want totally 9 bits of usage so it will be padded to 2 bytes.

If your structure was like

struct path_table_t {
   uint8_t lut_index : 1;
   uint8_t flag : 1;
};

int main()
{
   struct path_table_t p;

   printf("%d\n",sizeof(p));
}

You see here only 2 bits is required so your sizeof(struct) would be 1 byte which answers your question. Yes using bit fields can save memory as shown above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM