Unit – 8
STRUCTURE/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};
- Array elements are accessed using the Subscript variable , Similarly Structure members are accessed using dot [.] operator.
- (.) is called as “Structure member Operator”.
- Use this Operator in between “Structure variable”&“member name”
struct employee
{
int id;
char name[50];
float salary;
} ;
void main()
{
struct employee e= { 1, “ABC”, 50000 };
printf(“%d”, e. id);
printf(“%s”, e. name);
printf(“%f”, e. salary);
}
Members of a structure are always stored in consecutive memory locations but the memory occupied by each member may vary. Consider the following program:
#include<stdio.h>
struct book
{
char title[5];
int year;
double price;
};
int main()
{
struct book b1 = {"Book1", 1988, 4.51};
printf("Address of title = %u\n", b1.title);
printf("Address of year = %u\n", &b1.year);
printf("Address of price = %u\n", &b1.price);
printf("Size of b1 = %d\n", sizeof(b1));
// signal to operating system program ran fine
return 0;
}
Expected Output:
1 2 3 4 | Address of title = 2686728 Address of year = 2686736 Address of price = 2686744 Size of b1 = 24
|
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
DIFFERENCE BETWEEN STRUCTURE AND UNION
Structure | Union |
struct keyword is used | union keyword is used |
size of structure variable is the addition of all members of structure | size of union variable is the maximum size of among all members of union |
At a single time more than one member can accessible | At a single time only one member is accessible |
Reference
- Brian W. Kernighan And Dennis M. Ritchie, The C Programming Language, Prentice Hall Of India
- Yashwant Kanetkar, Let Us C, Bpb Publication