Sunday, November 10, 2013

C programs Structure union bit-fields!!

In C Programming Language, a structure is a user defined data type, which is a collection of different data types. Strutures, unions and bitfields are conceptually same, the difference in memory alignment. So defferentiate them, we need to get the size of the structure or union. Below are the sample c programs for each of them. Structures also do padding, Click here to get how padding works.

For below examples, size of int is 4 bytes(some systems allocates 2 or 8. ) and character takes 1 byte.

Structures in C: Below structure is collection of one char and one int data types. So total size should be 5 bytes(1+4). Because of memory alignment, it will allocate 4 bytes for char also, but 3 of 4 bytes in char variable or unused. So we will get the size of the structure as 8.

#include<stdio.h>
struct Sample{
  char c;
  int n;
};

int main()
{
 struct Sample s;
 printf("size is %u\n",sizeof(s));
}
Output: 
$ ./a.out 
 size is 8 

Unions in C: Unions are also same as structures. But the difference in memory alignment. The size of the union is the maximum size of the data type in the union. For example in the below example, union contains one char variable and one int variable, so char takes 1 byte and int takes 4 bytes, max of (1,4) is 4 , so size of the union is 4 bytes.

#include<stdio.h>
union Sample{
  char c;
  int n;
};

int main()
{
 union Sample s;
 printf("size is %u\n",sizeof(s));
}
Output: 
$ ./a.out 
 size is 4 

Bit fields in C: In the structure example we have seen, 3 bytes are unused because of memory alignment and padding. So to avoid these unused bytes, bit fields are introduced. We can specify, required bits using bitfields as shown below. We need to use colon(:) after the variable name, and specify the number of bits.

In the below example, we specified 2 bits for char and 2 bits for int, so total 4 bits (and not bytes), total size should be 4 bits, but because of memory alignment and padding, we will get 4 bytes as shown below. We will get 4 bytes until all the bits in the 4 bytes (32 bits) are used.

#include<stdio.h>
struct Sample{
  char c:2;
  int n:2;
};

int main()
{
 struct Sample s;
 printf("size is %u\n",sizeof(s));
}

Output: 
$ ./a.out 
 size is 4

No comments:

Popular Posts