Unit 10
Structures and Union
A structure can be considered as a template used for defining a collection of variables under a single name. Structures help programmers to group elements of different data types into a single logical unit (Unlike arrays which permit a programmer to group only elements of same data type).
- Why Use Structures
• Ordinary variables can hold one piece of information
• arrays can hold a number of pieces of information of the same data type.
For example, suppose you want to store data about a book. You might want to store its name (a string), its price (a float) and number of pages in it (an int).
If data about say 3 such books is to be stored, then we can follow two approaches:
Construct individual arrays, one for storing names, another for storing prices and still another for storing number of pages.
Use a structure variable.
Suppose we want to create a employee database. Then, we can define a structure
Called employee with three elements id, name and salary. The syntax of this structure is as
Follows:
Struct employee
{ int id;
Char name[50];
Float salary;
};
Note:
Struct keyword is used to declare structure.
Members of structure are enclosed within opening and closing braces.
Usually structure type declaration appears at the top of the source code file, before any variables or functions are defined or maintained in separate header file.
Declaration of Structure reserves no space.
It is nothing but the “ Template / Map / Shape ” of the structure .
Memory is created , very first time when the variable is created / Instance is created.
- Structure variable declaration:
We can declare the variable of structure in two ways
- Declare the structure inside main function
- Declare the structure outside the main function.
1. Declare the structure inside main function
Following example show you, how structure variable is declared inside main function
Struct employee
{
Int id;
Char name[50];
Float salary;
};
Int main()
{
Struct employee e1, e2;
Return 0;
}
In this example the variable of structure employee is created inside main function that e1 ,e2.
2. Declare the structure outside main function
Following example show you, how structure variable is declared outside the main function
Struct employee
{
Int id;
Char name[50];
Float salary;
}e1,e2;
- Memory allocation for structure
Memory is allocated to the structure only when we create the variable of structure.
Consider following example
- Structure Initialization
1. When we declare a structure, memory is not allocated for un-initialized variable.
2. Let us discuss very familiar example of structure student , we can initialize structure variable
In different ways –
Way 1 : Declare and Initialize
Struct student
{
Char name[20];
Int roll;
Float marks;
}std1 = { "Poonam",89,78.3 };
In the above code snippet, we have seen that structure is declared and as soon as after declaration we
Have initialized the structure variable.
Std1 = { "Poonam",89,78.3 }
This is the code for initializing structure variable in C programming
Way 2 : Declaring and Initializing Multiple Variables
Struct student
{
Char name[20];
Int roll;
Float marks;
}
Std1 = {"Poonam" ,67, 78.3};
Std2 = {"Vishal",62, 71.3};
In this example, we have declared two structure variables in above code. After declaration of variable we have initialized two variable.
Std1 = {"Poonam" ,67, 78.3};
Std2 = {"Vishal",62, 71.3};
Way 3 : Initializing Single member
Struct student
{
Int mark1;
Int mark2;
Int mark3;
} sub1={67};
Though there are three members of structure, only one is initialized , Then remaining two members
Are initialized with Zero. If there are variables of other data type then their initial values will be –
Data Type Default value if not initialized
Integer 0
Float 0.00
Char NULL
Way 4 : Initializing inside main
Struct student
{
Int mark1;
Int mark2;
Int mark3;
};
Void main()
{
Struct student s1 = {89,54,65};
- - - - --
- - - - --
- - - - --
};
When we declare a structure then memory won’t be allocated for the structure. i.e only writing below
Declaration statement will never allocate memory
Struct student
{
Int mark1;
Int mark2;
Int mark3;
};
We need to initialize structure variable to allocate some memory to the structure.
Struct student s1 = {89,54,65};
Structure is collection of different data type. An object of structure represents a single record in memory, if we want more than one record of structure type, we have to create an array of structure or object. As we know, an array is a collection of similar type, therefore an array can be of structure type.
Syntax for declaring structure array
Struct struct-name
{
Datatype var1;
Datatype var2;
- - - - - - - - - -
- - - - - - - - - -
Datatype varN;
};
Struct struct-name obj [ size ];
Example for declaring structure array
#include<stdio.h>
Struct Employee
{
Int Id;
Char Name[25];
Int Age;
Long Salary;
};
Void main()
{
Int i;
Struct Employee Emp[ 3 ]; //Statement 1
For(i=0;i<3;i++)
{
Printf("\nEnter details of %d Employee",i+1);
Printf("\n\tEnter Employee Id : ");
Scanf("%d",&Emp[i].Id);
Printf("\n\tEnter Employee Name : ");
Scanf("%s",&Emp[i].Name);
Printf("\n\tEnter Employee Age : ");
Scanf("%d",&Emp[i].Age);
Printf("\n\tEnter Employee Salary : ");
Scanf("%ld",&Emp[i].Salary);
}
Printf("\nDetails of Employees");
For(i=0;i<3;i++)
Printf("\n%d\t%s\t%d\t%ld",Emp[i].Id,Emp[i].Name,Emp[i].Age,Emp[i].Salary);
}
Output :
Enter details of 1 Employee
Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Age : 29
Enter Employee Salary : 45000
Enter details of 2 Employee
Enter Employee Id : 102
Enter Employee Name : Mukesh
Enter Employee Age : 31
Enter Employee Salary : 51000
Enter details of 3 Employee
Enter Employee Id : 103
Enter Employee Name : Ramesh
Enter Employee Age : 28
Enter Employee Salary : 47000
Details of Employees
101 Suresh 29 45000
102 Mukesh 31 51000
103 Ramesh 28 47000
In the above example, we are getting and displaying the data of 3 employee using
Array of object. Statement 1 is creating an array of Employee Emp to store the records
Of 3 employees.
Array within Structure
As we know, structure is collection of different data type. Like normal data type, It can
Also store an array as well.
Syntax for array within structure
Struct struct-name
{
Datatype var1; // normal variable
Datatype array [size]; // array variable
- - - - - - - - - -
- - - - - - - - - -
Datatype varN;
};
Struct struct-name obj;
Example for array within structure
Struct Student
{
Int Roll;
Char Name[25];
Int Marks[3]; //Statement 1 : array of marks
Int Total;
Float Avg;
};
Void main()
{
Int i;
Struct Student S;
Printf("\n\nEnter Student Roll : ");
Scanf("%d",&S.Roll);
Printf("\n\nEnter Student Name : ");
Scanf("%s",&S.Name);
S.Total = 0;
For(i=0;i<3;i++)
{
Printf("\n\nEnter Marks %d : ",i+1);
Scanf("%d",&S.Marks[i]);
S.Total = S.Total + S.Marks[i];
}
S.Avg = S.Total / 3;
Printf("\nRoll : %d",S.Roll);
Printf("\nName : %s",S.Name);
Printf("\nTotal : %d",S.Total);
Printf("\nAverage : %f",S.Avg);
}
Output :
Enter Student Roll : 10
Enter Student Name : Kumar
Enter Marks 1 : 78
Enter Marks 2 : 89
Enter Marks 3 : 56
Roll : 10
Name : Kumar
Total : 223
Average : 74.00000
In the above example, we have created an array Marks[ ] inside structure representing
3 marks of a single student. Marks[ ] is now a member of structure student and to
Access Marks[ ] we have used dot operator(.) along with object S.
Unions are quite similar to the structures in C. Union is also a derived type as
Structure. Union can be defined in same manner as structures just the keyword
Used in defining union in union where keyword used in defining structure was struct.
Union car
{
Char name[50];
Int price;
};
Union variables can be created in similar manner as structure variable.
Union car
{
Char name[50];
Int price;
}c1, c2, *c3;
OR;
Union car
{
Char name[50];
Int price;
};
-------Inside Function-----------
Union car c1, c2, *c3;
In both cases, union variables c1, c2 and union pointer variable c3 of type union
Car is created.
- Memory allocation for union
Like structure memory is allocated to union only when we create the variable of it.
The memory is allocated to union according to the largest data members of the union.
- Accessing members of an union
Array elements are accessed using the Subscript variable, Similarly Union members are accessed using dot [.] operator.
(.) is called as “union member Operator”.
Use this Operator in between “Union variable” & “member name”
Union employee
{
Int id;
Char name[50];
Float salary;
} ;
Void main()
{
Union employee e1= { 1, “ABC”, 50000 };
Printf(“%d”, e. Id);
Printf(“%s”, e. Name);
}
O/P- garbage value, ABC
Nested Structure
C provides us the feature of nesting one structure within another structure by using which, complex data types are created. For example, we may need to store the address of an entity employee in a structure. The attribute address may also have the subparts as street number, city, state, and pin code. Hence, to store the address of the employee, we need to store the address of the employee into a separate structure and nest the structure address into the structure employee. Consider the following program.
- #include<stdio.h>
- Struct address
- {
- Char city[20];
- Int pin;
- Char phone[14];
- };
- Struct employee
- {
- Char name[20];
- Struct address add;
- };
- Void main ()
- {
- Struct employee emp;
- Printf("Enter employee information?\n");
- Scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
- Printf("Printing the employee information....\n");
- Printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
- }
Output
Enter employee information?
Arun
Delhi
110001
1234567890
Printing the employee information....
Name: Arun
City: Delhi
Pincode: 110001
Phone: 1234567890
The structure can be nested in the following ways.
- By separate structure
- By Embedded structure
1) Separate structure
Here, we create two structures, but the dependent structure should be used inside the main structure as a member. Consider the following example.
- Struct Date
- {
- Int dd;
- Int mm;
- Int yyyy;
- };
- Struct Employee
- {
- Int id;
- Char name[20];
- Struct Date doj;
- }emp1;
As you can see, doj (date of joining) is the variable of type Date. Here doj is used as a member in Employee structure. In this way, we can use Date structure in many structures.
2) Embedded structure
The embedded structure enables us to declare the structure inside the structure. Hence, it requires less line of codes but it can not be used in multiple data structures. Consider the following example.
- Struct Employee
- {
- Int id;
- Char name[20];
- Struct Date
- {
- Int dd;
- Int mm;
- Int yyyy;
- }doj;
- }emp1;
Accessing Nested Structure
We can access the member of the nested structure by Outer_Structure.Nested_Structure.member as given below:
- e1.doj.dd
- e1.doj.mm
- e1.doj.yyyy
C Nested Structure example
Let's see a simple example of the nested structure in C language.
- #include <stdio.h>
- #include <string.h>
- Struct Employee
- {
- Int id;
- Char name[20];
- Struct Date
- {
- Int dd;
- Int mm;
- Int yyyy;
- }doj;
- }e1;
- Int main( )
- {
- //storing employee information
- e1.id=101;
- Strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
- e1.doj.dd=10;
- e1.doj.mm=11;
- e1.doj.yyyy=2014;
- //printing first employee information
- Printf( "employee id : %d\n", e1.id);
- Printf( "employee name : %s\n", e1.name);
- Printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n", e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
- Return 0;
- }
Output:
Employee id : 101
Employee name : Sonoo Jaiswal
Employee date of joining (dd/mm/yyyy) : 10/11/2014
Passing structure to function
Just like other variables, a structure can also be passed to a function. We may pass the structure members into the function or pass the structure variable at once. Consider the following example to pass the structure variable employee to a function display() which is used to display the details of an employee.
- #include<stdio.h>
- Struct address
- {
- Char city[20];
- Int pin;
- Char phone[14];
- };
- Struct employee
- {
- Char name[20];
- Struct address add;
- };
- Void display(struct employee);
- Void main ()
- {
- Struct employee emp;
- Printf("Enter employee information?\n");
- Scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.add.phone);
- Display(emp);
- }
- Void display(struct employee emp)
- {
- Printf("Printing the details....\n");
- Printf("%s %s %d %s",emp.name,emp.add.city,emp.add.pin,emp.add.phone);
- }
Structure as function argument
Structures can be passed as an argument to a function and can be used by the functions for performing operations on them. They are 3 methods by which the values of the structure can be transferred from one function to another.
Method 1
The first method is to pass each member of a structure as actual argument of the function call. The actual arguments are then treated independently as ordinary variables.
Example:
01 | #include<stdio.h> | |
02 | #include@lt;conio.h> | |
03 | Void main() | |
04 | { | |
05 | Struct stud | |
06 | { | |
07 | Char name[20]; | |
08 | Int age,no; | |
09 | }s; | |
10 |
| |
11 | Void display(char [],int,int); | |
12 | Printf(“\n Enter name of student :”); | |
13 | Gets(s.name); | |
14 | Printf(“\n Enter Age and roll Num:”); | |
15 | Scanf(“%d%d”,&s.age,&s.no); | |
16 | Clrscr( ); | |
17 | Display(s.name,s.age,s.no); | |
18 | Getch( ); | |
19 | } | |
20 | Void display(char ch[],int a, int n) | |
21 | { | |
22 | Printf(“\n Name of student :%s”,ch); | |
23 | Printf(“\n Age of Student :%d”,a); |
24 | Printf(“\n Roll Number :%d”,n); |
25 | } |
Method 2
In this method the entire structure is passed as an argument to a function. Since only a copy of the structure is sent, any changes made to structure members are not reflected int the original structure. It is therefore necessary for the function to return the entire structure back to the calling function.
General format of sending a copy of the structure is as follows
Functionname(Structure variable);
Example:
01 | #include<stdio.h> | |
02 | #include@lt;conio.h> | |
03 | Void main( ) | |
04 | { | |
05 | Struct emp | |
06 | { | |
07 | Char name[20]; | |
08 | Int id; | |
09 | Float sal; | |
10 | }; | |
11 | Void display(struct emp) ; | |
12 | Struct emp e; | |
13 | Clrscr(); | |
14 | Printf(“\n Enter name”); | |
15 | Gets(e.name); | |
16 | Printf(“\n Enter ID “); | |
17 | Scanf(“%d”,&e.id); | |
18 | Printf(“Enter salary :”); | |
19 | Scanf(“%f”,&e.sal); | |
20 | Display(e); | |
21 | Getch(); | |
22 | } | |
23 |
| |
24 | Void display(struct emp e) | |
25 | { | |
26 | Printf(“\n Employee name :%s”,e.ename); | |
27 | Printf(“\n Employee id :%d”,e.id); | |
28 | Printf(“\n Employee salary:%f”,e.sal); | |
29 | } |
Method 3
In this method,the address of the structure is passed to the function. Any changes made to the structure members are reflected on to the original structure. This is because pointers deal directly with the data stored in the memory.
Bit Fields
We know that an integer occupies 2 bytes of memory which is equal to 16 bits. Most of the time, we don’t use all the 16 bits to store the integer. So there is a wastage of memory. To serve this purpose, C supports the concept of sharing data items packed in a word of memory.
A bit field is a set of adjacent bits whose size can be from 1 to 16 bits in length. A word can therefore be divided into a number of bit fields. The name and size of bit fields are defined using a structure. The general form of bit fields definition is:
1 | Struct tag_name | |
2 | { | |
3 | Data_type name1: bit_length; |
4 | Data_type name2: bit_length; |
5 | ………………………. |
6 | ………………………. |
7 | }; |
The data type can either be int or unsigned int or signed int and the bit-length number bits used for specified name. The bit-length is decided by the range of value to be stored. The largest value that can stored is 2^n-1, where n is the bit-length.