Saturday, 8 February 2014

Union in c


                 Union

      Prev                                                                                              Next

      C Union is also like structure, i.e. collection of different data types which are grouped together. Each element in a union is called member.
……
  • Union and structure in C  are same in concepts, except allocating memory for their members.
  • Structure allocates storage space for all its members separately.
  • Whereas, Union allocates one common storage space for all its members
  • We can access only one member of union at a time. We can’t access all member values at the same time in union. But, structure can access all member values at the same time. This is because, Union allocates one common storage space for all its members. Wheras Structure allocates storage space for all its members separately.
  • Many union variables can be created in a program and memory will be allocated for each union variable separately.
  • Below table will help you how to form a C union, declare a union, initializing and accessing the members of the union.
Type Using normal variable Using pointer variable
Syntax union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example union student
{
int  mark;
char name[10];
float average;
};
union student
{
int  mark;
char name[10];
float average;
};
Declaring union variable union student report; union student *report, rep;
Initializing union variable union student report = {100, “Mani”, 99.5}; union student rep = {100, “Mani”, 99.5};report = &rep;
Accessing union members report.mark
report.name
report.average
report  -> mark
report -> name
report -> average

Example program for C union:

Output:

Union record1 values example
Name :
Subject :
Percentage : 86.500000  Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000

Explanation for above C union program:

      There are 2 union variables declared in this program to understand the difference in accessing values of union members.
Record1 union variable:
  • “Raju” is assigned to union member “record1.name” . The memory location name is “record1.name” and the value stored in this location is “Raju”.
  • Then, “Maths” is assigned to union member “record1.subject”. Now, memory location name is changed to “record1.subject” with the value “Maths” (Union can hold only one member at a time).
  • Then, “86.50” is assigned to union member “record1.percentage”. Now, memory location name is changed to “record1.percentage” with value “86.50”.
  • Like this, name and value of union member is replaced every time on the common storage space.
  • So, we can always access only one union member for which value is assigned at last. We can’t access other member values.
  • So, only “record1.percentage” value is displayed in output. “record1.name” and “record1.percentage” are empty.
Record2 union variable:
  • If we want to access all member values using union, we have to access the member before assigning values to other members as shown in record2 union variable in this program.
  • Each union members are accessed in record2 example immediately after assigning values to them.
  • If we don’t access them before assigning values to other member, member name and value will be over written by other member as all members are using same memory.
  • We can’t access all members in union at same time but structure can do that.

Example program – Another way of declaring C union:

    In this program, union variable “record” is declared while declaring union itself as shown in the below program.

Output:

Name :
Subject :
Percentage : 86.500000

Note:

      We can access only one member of union at a time. We can’t access all member values at the same time in union. But, structure can access all member values at the same time. This is because, Union allocates one common storage space for all its members. Where as Structure allocates storage space for all its members separately.

Difference between structure and union in C:

S.no
C Structure
C Union
1
Structure allocates storage space for all its members separately.
Union allocates one common storage space for all its members.
Union finds that which of its member needs high storage space over other members and allocates that much space
2 Structure occupies higher memory space. Union occupies lower memory space over structure.
3 We can access all members of structure at a time. We can access only one member of union at a time.
4 Structure example:
struct student
{
int mark;
char name[6];
double average;
};
Union example:
union student
{
int mark;
char name[6];
double average;
};
 5 For above structure, memory allocation will be like below.
int mark – 2B
char name[6] – 6B
double average – 8B 
Total memory allocation = 2+6+8 = 16 Bytes
For above union, only 8 bytes of memory will be allocated since double data type will occupy maximum space of memory over other data types. 
Total memory allocation = 8 Bytes

      Prev                                                                                              Next

 .


Typedef in c


                Typedef

      Prev                                                                                              Next

  • Typedef is a keyword that is used to give a new symbolic name for the existing name in a C program. This is same like defining alias for the commands.
  • ……
    ……
  • Consider the below structure.
struct student
{
         int mark [2];
         char name [10];
         float average;
}
  • Variable for the above structure can be declared in two ways.
1st way  :
struct student record;       /* for normal variable */
struct student *record;     /* for pointer variable */
2nd way :
typedef struct student status;
  • When we use “typedef” keyword before struct <tag_name> like above, after that we can simply use type definition “status” in the C program to declare structure variable.
  • Now, structure variable declaration will be, “status record”.
  • This is equal to “struct student record”. Type definition for “struct student” is status. i.e. status = “struct student”

An alternative way for structure declaration using typedef in C:

typedef struct student
{
         int mark [2];
         char name [10];
         float average;
} status;
  • To declare structure variable, we can use the below statements.
status record1;                 /* record 1 is structure variable */
status record2;                 /* record 2 is structure variable */

Example program for C typedef:

Output:

Id is: 1
Name is: Raju
Percentage is: 86.500000
  • Typedef can be used to simplify the real commands as per our need.
  • For example, consider below statement.
typedef long long int LLI;
  • In above statement, LLI is the type definition for the real C command “long long int”. We can use type definition LLI instead of using full command “long long int” in a C program once it is defined.

Another example program for C typedef:

 Output:

Storage size for long long int data type : 8

      Prev                                                                                              Next

.


C – Structure Padding


C – Structure Padding

      Prev                                                                                               Next

  • 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.
  • To make use of this advantage of processor, data are always aligned as 4 bytes package which leads to insert empty addresses between other member’s address.
  • Because of this structure padding concept in C, size of the structure is always not same as what we think.
      For example, please consider below structure that has 5 members.
..
struct student
{
       int id1;
       int id2;
       char a;
       char b;
       float percentage;
};
..
  • As per C concepts, int and float datatypes occupy 4 bytes each and char datatype occupies 1 byte for 32 bit processor. So, only 14 bytes (4+4+1+1+4) should be allocated for above structure.
  • But, this is wrong.  Do you know why?
  • Architecture of a computer processor is such a way that it can read 1 word from memory at a time.
  • 1 word is equal to 4 bytes for 32 bit processor and 8 bytes for 64 bit processor. So, 32 bit processor always reads 4 bytes at a time and 64 bit processor always reads 8 bytes at a time.
  • This concept is very useful to increase the processor speed.
  • To make use of this advantage, memory is arranged as a group of 4 bytes in 32 bit processor and 8 bytes in 64 bit processor.
  • Below C program is compiled and executed in 32 bit compiler. Please check memory allocated for structure1 and structure2 in below program.

Example program for structure padding in C:

Output:

size of structure1 in bytes : 16  Address of id1 = 1297339856
Address of id2 = 1297339860
Address of name = 1297339864
Address of c = 1297339865
Address of percentage = 1297339868
size of structure2 in bytes : 20
Address of id1 = 1297339824
Address of name = 1297339828
Address of id2 = 1297339832
Address of c = 1297339836
Address of percentage = 1297339840

Structure padding analysis for above C program:

Memory allocation for structure1:

Structure padding in C 1_new
    • In above program, memory for structure1 is allocated sequentially for first 4 members.
    • Whereas, memory for 5th member “percentage” is not allocated immediate next to the end of member “c”.
    • There are only 2 bytes remaining in the package of 4 bytes after memory allocated to member “c”.
    • Range of this 4 byte package is from 1297339864 to 1297339867.
    • Addresses 1297339864  and 1297339865 are used for members “name and c”. Addresses 1297339866  and 1297339867 only is available in this package.
    • But, member “percentage” is datatype of float and requires 4 bytes. It can’t be stored in the same memory package as it requires 4 bytes. Only 2 bytes are free in that package.
    • So, next 4 byte of memory package is chosen to store percentage data which is from 1297339868 to 1297339871.
    • Because of this, memory 1297339866 and 1297339867 are not used by the program and those 2 bytes are left empty.
    • So, size of structure1 is 16 bytes which is 2 bytes extra than what we think. Because, 2 bytes are left empty.

 Memory allocation for structure2:

Structure padding in C 2_new
    • Memory for structure2 is also allocated as same as above concept. Please note that structure1 and structure2 are same. But, they differ only in the order of the members declared inside the structure.
    • 4 bytes of memory is allocated for 1st structure member “id1″ which occupies whole 4 byte of memory package.
    • Then, 2nd structure member “name” occupies only 1 byte of memory in next 4 byte package and remaining 3 bytes are left empty. Because, 3rd structure member “id2″ of datatype integer requires whole 4 byte of memory in the package. But, this is not possible as only 3 bytes available in the package.
    • So, next whole 4 byte package is used for structure member “id2″.
    • Again, 4th structure member “c” occupies only 1 byte of memory in next 4 byte package and remaining 3 bytes are left empty.
    • Because, 5th structure member “percentage” of datatype float requires whole 4 byte of memory in the package.
    • But, this is also not possible as only 3 bytes available in the package. So, next whole 4 byte package is used for structure member “percentage”.
    • So, size of structure2 is 20 bytes which is 6 bytes extra than what we think. Because, 6 bytes are left empty.

How to avoid structure padding in C?

    • #pragma pack ( 1 ) directive can be used for arranging memory for structure members very next to the end of other structure members.
    • VC++ supports this feature. But, some compilers such as Turbo C/C++ does not support this feature.
    • Please check the below program where there will be no addresses (bytes) left empty because of structure padding.

Example program to avoid structure padding in C:

Output:

size of structure1 in bytes : 14  Address of id1 = 3438103088
Address of id2 = 3438103092
Address of name = 3438103096
Address of c = 3438103097
Address of percentage = 3438103098
size of structure2 in bytes : 14
Address of id1 = 3438103072
Address of name = 3438103076
Address of id2 = 3438103077
Address of c = 3438103081
Address of percentage = 3438103082


      Prev                                                                                               Next