I don't know your are asking about bit fields or data member of a structure and how they are stored in the memory.
So I am explaining both of them.
Both are them are store in the memory based on where you have declare them i,e (Global, Static, Local, Dynamically)
1. For global and static -- the memory area is allocated on data segment.
2. Local --> on stack segment.
3. Dynamic ---> on heap segment.
I assume you know about this. And you are not asking about this explanation.
Example:
struct example
{
long long ll; // @ 0 i.e (0 to 7)
int i; // @ 8 (8 to 11)
short s; // @ 12 (12 to 13)
char ch1; // @ 14 (14)
char ch2; // @ 15 (15)
} EX;
int main()
{
printf("Sizeof_Structure : %d\n", sizeof(EX)); //it will give you 16 you can follow the comments in structure above.
printf("offsets : ll = %ld; i = %ld; s = %ld; ch1 = %ld; ch2 = %ld\n",
(long)offsetof(struct EX, ll), (long)offsetof(struct EX, i),
(long)offsetof(struct EX, s), (long)offsetof(struct EX, ch1),
(long)offsetof(struct EX, ch2));
return 0;
}
output :
Sizeof_Structure : 16
offsets : ll = 0; i = 8; s = 12; ch1 = 14; ch2 = 15
/*
Here all is ok in the above code.
to check just add one more char ch3. as a new member to the above structure and then calculate the
total size. it will be either 20 ro 24 (based on the boundary (usually 4 or 8 bytes).
But the actual size is 17 only, this because of structure padding.
*/
In order to align the data in memory, one or more empty bytes (addresses) are inserted (or left empty) between memory addresses which are allocated for other structure members while memory allocation. This concept is called structure padding.
Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit processor) from memory at a time.
BIT Fields in Structure: It allow the packing of data in a structure. This is especially useful when memory or data storage is at a premium.
So you can do this by defining the bit-length is the structure, i.e you are telling the your going to need that much size for the data member of the object.
For example:
struct bit_field {
int a:1;
int b:2;
int c:1;
// Add your data members (bit-field variable) and validate the size.
}BIT;
int main()
{
printf("sizeof_bit_field : %d\n", sizeof(BIT));
return 0;
}
output : 4 (Bytes) not bit.
/*
Here in the above structure bit_field you are specifying the bit length for each data member, i.e
"a" will contains only 1 bit of size irrespective of its data type i.e int (which size is 4 mostly).
"b" will be of size 2 bit,
"c" will be of size 1 bit.
So here will have used only 4 bits. and the sizeof (int) will is 4 (bytes --> 32 bit), so we can use all
the remaining bits i.e (32 -4 = 28 bit). you can use different data type also (char, double, float etc).
*/
Do change in (play with) the bit_field structure (add 1 or n number of new members in the structure
with different bit-field value and check the size of the structure.
:) Have fun, keep coding.