You are on page 1of 31

STRUCTURE

INDEX

Structure Introduction
1.0. Differences between array and structure
1.1. Structure Declaration and Definition
1.2. Structure Variable declaration
1.3. Initialization of structure members
1.4. Copying and Comparing Structures
1.5. Accessing of the structure variables
1.6. Array of Structures
1.7. Nested Structures
1.8. Pointer to Structures
1.8.1. Declare and initialize a pointer variable to a structure
1.8.2. Accessing structure members using pointer variable
1.8.3. Pointer variable to array of structure and nested structures
1.8.4. Pointer with in Structures

1.9. Structures and Functions


1.9.1. Passing Individual Member
1.9.2. Passing the Entire Structure
1.9.3. Passing structures through Pointers

10. Self-Referential Structures


11. Review questions on structures
12. Unions

By:
P.Chakradhar
Asst.Prof. Dept. of CSE.
GITAM University
HTP Campus.
E-Mail: chakri540@gitam.edu

GITAM UNIVERSITY

Page 0

1. Structure Introduction
A structure is basically a user-defined data type that can store related, probably of different data types
together. A structure is similar to records. It stores related information about an entity having a single name.
Each element in a structure is called structure member or structure field. Structure helps to organize complex
data in a more meaningful way.

PROBLEM STATEMENT: A school teacher wants to save his students details in a record.
Student details like
1. Student Name String Type Data,
2. Student Roll number Number Type Data
3. Student class Number Type Data, 4. Student Phone Number Number Type Data
Help to teacher to do same by using a computer program.
SOLUTION:
STEP 1: Declare Character array to store Student name.
STEP 2: Declare Integer variable to store Student roll number.
STEP 3: Declare Integer variable to store Student class.
STEP 4: Declare Double variable to store Student Phone number.
SOLUTION ANALYSIS:
The solution which is suggested is quite good where student count is 1 or 2.
But if student count is huge?
NUMBER OF STUENTS
50
100
200

NUMBER OF ARRAYS TO BE
DECLARED
50*4=200
100*4=400
200*4=800

Where the student count is increasing the array declarations also exponentially increasing. So by
this analysis we came to know that the solution which suggested is not accurate.
BEST SOLUTION:
1. Declare a template with required data types.
2. Create many number of instances for this template as many as we required.
3. Each instance give to each student.
This best solution can be achieve in programming scenario by using STRUCTURE concept.

GITAM UNIVERSITY

Page 1

1.0. Differences between Arrays and Structures


ARRAYS
1. An array represents a group of elements of
same data type.
2. It is very difficult to organize complex data by
using arrays concept.
3. Memory will be allocated for the array at the
time of its declaration.
4. There is no special keyword in declaration of
an array.
Syntax: int Arrayname[ArraySize].

5. An array elements are referred by index.


6. An array is a derived data type.

STRUCTURES
1. A structure represents a group of elements of
different data types having a single name.
2. It is easy to organize complex data by using
structure concept.
3. Memory is allocated only at the time of declaration
of structure variables.
4. A special keyword struct is used in declaration of
structure.
Syntax: struct StructureIdentifier
{
Structure Member1;
Structure Member2;
......
}Structure Variables;
5. A structure elements can be referred by its structure
variable name.
6. A structure is a user defined data type.

1.1. Structure Declaration and Definition


A structure is declared using the keyword struct . Like all data types, structures must be declared before
using it. C has two ways to declare a structure.
1. Tagged structure declaration.
2. Typedef structure declaration.

1.1.1. Tagged structure declaration


A Tagged structure declaration can be used to define structure variables and return type. It is starts with
the keyword struct. The second element is the tag. The tag is the identifier for the structure.

GITAM UNIVERSITY

Page 2

1.1.2. Typedef structure declaration


The typedef structure declaration differs from the tagged structure declaration in two ways. First, the
keyword typedef added to the beginning of the definition. Second, an identifier is required at the end of the
block and before the semicolon.

NOTE: Memory is not allocated for the structure at the time of its declaration. It just gives a template
that conveys to the C compiler how the structure is laid out in memory and gives details of the member
names. Like any other data type; memory is allocated for the structure when we declare a variable of
the structure.

1.2. Structure Variable Declaration


After a structure has been declared, we can declare variables using it. Declaration of structure variable can be
done either as global variables or as local variables for a program.

1.2.1. Global declaration of structure variables


struct STUDENT
{
char Sname[20];
int
Srollnumber;
int
Sclass;
double Sphonenumber;
}stu1,stu2; // Global declaration
of structure variables
main( )
{
.........;
.........;

struct STUDENT
{
char Sname[20];
int
Srollnumber;
int
Sclass;
double Sphonenumber;
};
struct STUDENT stu1,stu2;
// Global declaration of structure variables
main( )
{
.........;
.........;

}
Structure variable global declaration in TAGGED structure declaration.
GITAM UNIVERSITY

Page 3

typedef struct
{
char
Sname[20];
int
Srollnumber;
int
Sclass;
double
Sphone;
}STUDENT;
STUDENT stu1,stu2; // Global declaration of structure variables
main( )
{
...........;
...........;
}

Structure variable global declaration in typedef structure declaration.


1.2.2. Local declaration of structure variable
struct STUDENT
{
char Sname[20];
int Srollnumber;
int Sclass;
double Sphonenumber;
};

typedef struct
{
char Sname[20];
int
Srollnumber;
int
Sclass;
double
Sphonenumber;
}STUDENT;

main( )
{
struct STUDENT stu1,stu2;
..............;
. . . . . . . . . . . . . .;
}

main( )
{
STUDENT stu1,stu2;
. . . . . . . . . . . . .;
. . . . . . . . . . . . .;
}

Structure variable local declaration


in tagged structure declaration.

Structure variable local declaration in


typedef structure declaration.

NOTE: A structure declaration must be terminated with a semicolon ( ; ).

GITAM UNIVERSITY

Page 4

1.3. Initialization of structure members


Structure variable can be initialized in two ways: (i) Static Initialization (ii) Dynamic Initialization

1.3.1. Static structure variable initialization


The structure variable static initialization is similar to the rules for array initialization. Initializing a structure
means assigning some constants to the members of the structure. The initializers are enclosed in braces and
separated by commas. They must match their corresponding types in the structure definition. The nested
structure initializers must be enclosed in their own set of braces.
typedef struct
{
char Sname[20];
int
Srollnumber;
int
Sclass;
double
Sphonenumber;
}STUDENT;
main( )
{
STUDENT stu1,stu2;
stu1={ SRINIVAS , 31, 4, 123456};
stu2={ KRISHNA , 24, 10, 245315};
}

NOTE: When one or more initializers are missing at static initialization of structure variable the structure
members will be assigned null values, zero (0) for integers and floating-point numbers and null (\0)
character for characters and strings.

1.3.2. Dynamic structure variable initialization


Dynamic initialization to a structure variable can be done by using input function scanf( ). Before going
in detail we must know about operators used in structures.
typedef struct
{
char Sname[20];
int
Srollnumber;
int
Sclass;
double
Sphonenumber;
}STUDENT;
main( )
{
STUDENT stu1,stu2;
scanf(%s %d %d %d,stu1.Sname,&stu1.Srollnumber,&stu1.Sclass,&stu1.Sphonenumber);
scanf(%s %d %d %d,stu2.Sname,&stu2.Srollnumber,&stu2.Sclass,&stu2.Sphonenumber);
}

GITAM UNIVERSITY

Page 5

1.4. Copying and Comparing Structures


We can assign a structure to another structure of the same type. For example, if we have two structure
variables stu1 and stu2 of type structure STUDENT given as,
struct STUDENT stu1={ SRINIVAS , 31, 4, 123456};
Then to assign one strucure variable to another we will write, stu2 = stu1; . This statement initializes the
members of stu2 with the constants of members of stu1;
Sample Code:
main( )
{
STUDENT stu1,stu2;
stu1={ SRINIVAS, 31 , 4 , 123456 };
stu2 = stu1;
printf(%3s %3d %3d %3e ,stu2.Sname,stu2.Srollnumber,stu2.Sclass,stu2.Sphonenumber);
}
OUTPUT: SRINIVAS 31 4 123456

C does not permit comparison of one structure variable with another. However, individual members of
one structure variable can be compared with individual members of another structure variable. When we
compare one structure member with anothers member, the comparison will behave like any other ordinary
variable comparison.
Sample Code:

if ( stud1.Srollnumber > stud2.Srollnumber)


printf( First Student roll number is grater );
else
printf( Second Student roll number is grater );

1.5. Accessing of the structure variables


Before going to learn accessing of the structure variable members, it is must to know about operators used
in structures.

1.5.1. Operators used in structures


Two operators are used to access members of structure variables.
i)
The structure member operator ( ), also called as direct selection operator, dot operator or
period operator.
ii)
The structure pointer operator ( ), also called arrow operator.
The member operator accesses a structure member via the structure variable name. Member operator play a
vital role in dynamic initialization of structure variables. To refers to a member in a structure we need to refer to
both the structure variable and structure member respectively.
The pointer operator consisting of a minus sign (-) and a greater than ( > ) sign without space in between.It
accesses a structure member via a pointer to the structure.
The syntax of accessing a member of a structure
GITAM UNIVERSITY

Struct_var . member_name
Page 6

NOTE:
1. C does not allow declaration of variables at the time of creating a typedef definition. So structure
variables must be declared in an independent statement.
2. A member of the structure cannot be accessed directly using its name. Rather you must use the
structure variable name followed by dot operator before specifying the member name.

Example 1: Write a program using structures to read and display the information about a student. Where as
structure declaration in local scope.
#include<stdio.h>
// Preprocessing command to include header file into program.
void main( )
// main function declaration with void return type .
{
struct STUDENT
{
int roll_no;
char name[30];
// Structure template local declaration with TAGGED declaration style.
float fees;
char DOB[11];
// Structure members declaration.
};
struct STUDENT stu1; // Declaration of structure variable
printf( \n Enter the student roll number: );
scanf(%d,&stu1.roll_no);
printf(\n Enter student name: );
scanf(%s,stu1.name);
// Dynamic initialization of variable members.
printf(\n Enter the fees: );
scanf(%f,&stu1.fees);
printf(\n Enter the Date of Birth[DD:MM:YYYY]: );
scanf(%s,stu1.DOB);
printf(\n********** STUDENT DETAILS**********);
printf(\n Student Roll number = %d,stu1.roll_no);
printf(\n Student Name = %s ,stu1.name);
//Accesses & printing the values of members of stu1.
printf(\n FEES = %f , stu1.fees);
printf(\n Student date of birth= %s , stu1.DOB);
} // END of main function
OUTPUT:
Enter the student roll number: 10
Enter student name: Rama krishna
Enter the fees: 180000
Enter the Date of Birth[DD-MM-YYYY] : 26 10 1987
********** STUDENT DETAILS **********
Student Roll number = 10
Student Name = Rama krishna
FEES = 180000
Student date of birth = 26 10 1987
GITAM UNIVERSITY

// User INPUT values

// Program output values


Page 7

Example 2 : Write a c program to read , add two complex numbers and display the result. Where as
structure declaration in global scope use typedef declaration style.
#include<stdio.h>
typedef struct
{
int real;
int imag;
} COMPLEX;
COMPLEX C1, C2, Result_C;
void main( )
{
printf(\n Enter the real and imaginary parts of the first complex number: );
scanf(%d%d, &C1.real , &C1.imag);
printf(\n Enter the real and imaginary parts of the second complex number: );
scanf(%d%d, &C2.real , &C2.imag);
Result_C.real = C1.real + C2.real;
Result_C.imag = C1.imag + C2.imag;
printf(\n);
printf( \n The sum of two complex numbers is: %d + %di ,Result_C.real,Result_C.imag);
}
OUTPUT:
Enter the real and imaginary parts of the first complex number : 2 4
Enter the real and imaginary parts of the second complex number : 3 5
The sum of two complex numbers is: 5 + 9i

PRACTICE PROBLEMS:
1. Write a C program, using structure, to find the biggest of three integer numbers.
2. Write a C program to enter two points and then calculate the distance between them.
3. Write a program using structures to read and display the information about an employee.
Employee attributes: 1. Employee name
2. Employee number
3. Employee Date of Joining
4. Employee Salary
4. Write a C program using structures to print electricity bill.
Electricity bill attributes: 1. Meter number
2. Owner name
3. House number
4. No. of units consumed
5. Bill amount
GITAM UNIVERSITY

Page 8

1.6. Array of Structures


Before starting of array of structures, let us first analyze, where we would need array of structures.
Consider example 1 program, in a class, we do not have just one student. But there may be at least 40 students.
So here we can have a common structure definition for all the 40 students. This would be possible when we will
make an array of the structure. An array of a structure is declared in the same way as we had declared an array
of built-in data type.
struct Struct_Identifier
{
data_type member_name1;
The general syntax for declaring an array of a structure.
data_type member_name2;
data_type member_name3;
...................;
};
struct struct_Identifier struct_var[size];
Example 3: Write a program using structures to read and display the information of all the students in the
class.
#include<stdio.h>
void main( )
{
struct STUDENT
{
int
roll_no;
char name[30];
int
fees;
char DOB[10];
};
int n,i;
printf(\n Enter the number of students: );
scanf(%d,&n);
struct STUDENT stud[n]; // Array of structure declaration.
for(i=0 ; i<n ; i++)
{
printf(\n Enter %d student details: ,i+1);
printf(\n Enter the roll number: );
scanf(%d,&stud[i].roll_no);
printf(\n Enter Name: );
scanf(%s,stud[i].name);
printf(\n Enter the fees: );
scanf(%d,&stud[i].fees);
printf(\n Enter the date of birth[DD-MM-YYYY]: );
scanf(%s,stud[i].DOB);
}
Printf( \n ********** STORED STUDENT DETAILS ********** );

GITAM UNIVERSITY

Page 9

for ( i=0 ; i<n ; i++)


{
printf(\n);
printf (\n Details of %d student:,i+1);
printf(\n\t Roll Number = %d, stud[i].roll_no);
printf(\n\t Name = %s, stud[i].name);
printf(\n\t FEES = %d, stud[i].fees);
printf(\n\t Date of birth = %s, stud[i].DOB);
}
}// close of main Function
OUTPUT:
Enter the number of students: 3
Enter 1 student details:
Enter the roll number: 101
Enter Name: Vamsi
Enter the fees: 45000
Enter the date of birth [DD-MM-YYYY]: 12 02 1992
Enter 2 student details:
Enter the roll number: 102
Enter Name: Krishna
Enter the fees: 45000
Enter the date of birth [DD-MM-YYYY]: 12 12 1993
Enter 3 student details:
Enter the roll number: 103
Enter Name: Srinivas Rao
Enter the fees: 20000
Enter the date of birth [DD-MM-YYYY]: 23 08 1992
********** STORED STUDENT DETAILS **********
Details of 1 student:
Roll Number = 101
Name = Vamsi
FEES = 45000
Date of birth = 12 02 1992
Details of 2 student:
Roll Number = 102
Name = Krishna
FEES = 45000
Date of birth = 12 12 1993
Details of 3 student:
Roll Number = 103
Name = Srinivas Rao
FEES = 20000
Date of birth = 23 12 1992

GITAM UNIVERSITY

// USER INPUT DATA

// Program OUTPUT

Page 10

NOTE: It is an error to omit array subscripts when referring to individual structure variables of an array
of structures.

PRACTICE PROBLEMS:
1. Write a program using structures to read and display the information about 10 employees.
Employee attributes: 1. Employee name
2. Employee number
3. Employee Date of Joining
4. Employee Salary (hint: use Array of structure)
2. Write a C program using structures to print 10 electricity bill.
Electricity bill attributes: 1. Meter number
2. Owner name
3. House number
4. No. of units consumed
5. Bill amount
(hint: use Array of structure)
3. Write a program to read and display the information of all the students in the class. Then edit the
details of the ith student and redisplay the entire information.
Student attributes: 1. Student name
2. Student roll number
3. Student fees
4. Student date of birth

1.7. Nested Structures


When a structure includes another structure, it is a nested structure. There is no limit to the number of
structures that can be nested. In nested structures each low level structures are declared separately and then
grouped in the high level structure. We must declare the innermost structure first, then the next level, working
upward toward the outer structure.
SAMPLE CODE: Declare STAMP structure which contains two nested structures DATE and TIME.
typedef struct
{
int day;
int month;
int year;
}DATE;
Low Level structure1

GITAM UNIVERSITY

typedef struct
{
int seconds;
int minutes;
int hours;
}TIME;
Low Level Structure2

typedef struct
{
DATE date;
TIME time;
}STAMP;

High level Structure

Page 11

Example 4: Write a program to read and display information of an employee, using a nested structure.
#include< stdio.h >
typedef struct
{
int day;
int month;
int year;
}DOJ; // DOJ = Date of joining
typedef struct
{
char name[30];
int
ID;
DOJ doj;
float salary;
}EMPLOYEE;
void main( )
{
int n,i;
printf(\n Enter the number of Employees: );
scanf(%d,&n);
EMPLOYEE emp[n]; // Array of structures declaration.
for( i=0 ; i<n ; i++)
{
printf(\n Enter %d Employee details: );
printf(\n\t Enter Employee Name: );
scanf(%s,emp[i].name);
printf(\n\t Enter Employee ID: );
scanf(%d,&emp[i].ID);
printf(\n\t Enter Employee Date of Joining: );
scanf(%d %d %d, &emp[i].doj.day, &emp[i].doj.month, &emp[i].doj.year); // Nested Structure printf(\n\t Enter Employee Salary: );
- initialization.
scanf(%f,&emp[i].salary);
}
printf(\n ********** STORED INFORMATION **********);
for( i=0 ; i<n ; i++ )
{
printf(Details of %d Employee: );
printf(\n\t Employee Name = %s,emp[i].name);
printf(\n\t Employee ID = %d,emp[i].ID);
printf(\n\t Employee Date of Joining = %d-%d-%d,emp[i].doj.day,emp[i].doj.month,emp[i].doj.year);
printf(\n\t Employee Salary =%f ,emp[i].salary);
}
}

GITAM UNIVERSITY

Page 12

OUTPUT:
Enter the number of Employees: 2
Enter 1 Employee details:
Enter Employee Name: Srinivas Rao
Enter Employee ID: 10102
Enter Employee Date of Joining: 1 6 2013
Enter Employee Salary: 40000
Enter 2 Employee details:
Enter Employee Name: Pavan Kumar
Enter Employee ID: 10125
Enter Employee Date of Joining: 3 6 2013
Enter Employee Salary: 50000
********** STORED INFORMATION **********
Details of 1 Employee:
Employee Name = Srinivas Rao
Employee ID = 10102
Employee Date of Joining = 1 6 2013
Employee Salary = 40000

//User Input

// Program Output

Details of 2 Employee:
Employee Name = Pavan Kumar
Employee ID = 10125
Employee Date of Joining = 3 6 2013
Employee Salary = 50000

PRACTICE PROBLEMS:
1. Write a program using nested structures to read and display the information about 10 Students.
Employee attributes: 1. Student name
2. Student Roll number
3. Student Date of Joining // low level structure.
4. Student Fees
2. Write a C program using nested structures to print 10 electricity bill.
Electricity bill attributes:
1. Meter number
2. House address (Owner name, House number, Street Name, City) //Low Level Structure
3. No. of units consumed
4. Bill amount

GITAM UNIVERSITY

Page 13

1.8. Pointer to Structures


The address of a given structure variable can be obtained by using address operator &. We can use
pointer to structures to access structure members by using their address. The operator which is used in this
context is arrow operator .
Example 5:
struct STUDENT
{
char Sname[30];
int
SRollno;
};
struct STUDENT stu1;

In this example we can obtained the address of stu1


structure variable as &stu1. We required a same data
type pointer variable to store this address.

void main( )
{ . . . . . .;
. . . . . .;
}

1.8.1. Declare and initialize a pointer variable to a structure


We can declare a pointer variable of structure type in three ways:
Method 1: struct STUDENT
{ char Sname[30]; /* Second variable declared as pointer variable of STUDENT
int SRollno;
type with global scope and initialize to address of variable
}stu1, * ptr = &stu1 ; stu1 of STUDENT type . */

Method 2: struct STUDENT


{ char Sname[30];
/*Second variable declared as pointer variable of
int SRollno;
STUDENT type with global scope and initialize to
};
address of variable stu1 of STUDENT type . */
struct STUDENT stu1, * ptr = &stu1;
void main( )
{...
... }
Method 3: struct STUDENT
{ char Sname[30];
/* Second variable declared as pointer variable of
int SRollno;
STUDENT type with local scope and initialize to
};
address of variable stu1 of STUDENT type . */
void main( )
{
struct SUDENT stu1, * ptr = &stu1;
}

GITAM UNIVERSITY

Page 14

1.8.2. Accessing structure members using pointer variable


Accessing structure member using pointer through the use of a special operator called arrow operator.
Example 6: Write a program using structures to read and display the information about a student. Where
structure members are accessed by their address.
#include<stdio.h>
// Preprocessing command to include header file into program.
void main( )
// main function declaration with void return type .
{
struct STUDENT
{
int roll_no;
char name[30];
// Structure template local declaration with TAGGED declaration style.
float fees;
char DOB[11];
// Structure members declaration.
};
struct STUDENT stu1,* ptr ; // Declaration of structure variable and Pointer variable.
ptr = &stu1;
// Initialize stu1 address to pointer variable.
printf( \n Enter the student roll number: );
scanf(%d,&ptrroll_no);
printf(\n Enter student name: );
scanf(%s,ptrname);
/* Dynamic initialization of structure variable
printf(\n Enter the fees: );
members with reference of variable address.*/
scanf(%f,&ptrfees);
printf(\n Enter the Date of Birth[DD:MM:YYYY]: );
scanf(%s,ptrDOB);
printf(\n********** STUDENT DETAILS**********);
printf(\n Student Roll number = %d,ptrroll_no);
printf(\n Student Name = %s ,ptrname);
/* Printing the values of members of stu1
printf(\n FEES = %f , ptrfees);
by using stu1 address. */
printf(\n Student date of birth= %s , ptrDOB);
} // END of main function
OUTPUT:
Enter the student roll number: 10
Enter student name: Rama krishna
Enter the fees: 180000
Enter the Date of Birth[DD-MM-YYYY] : 26 10 1987
********** STUDENT DETAILS **********
Student Roll number = 10
Student Name = Rama krishna
FEES = 180000
Student date of birth = 26 10 1987

GITAM UNIVERSITY

// User INPUT values

// Program output values

Page 15

1.8.3. Pointer variable to array of structure and nested structures


Example 7: Write a C program to find average of six subjects for all students in class along with student
name and student roll number. Use pointer to nested structures.
#include<stdio.h>
typedef struct
//Inner structure declaration
{
int marks[6];
}RESULT;
typedef struct // Outer structure declaration
{ char Sname[30];
int
Srollno;
RESULT res;
float
avg; } STUDENT;
void main( )
{
int n;
printf(\n Enter number of students: );
scanf(%d,&n);
STUDENT stu[n], * ptr ; // Declaration of array of structure and structure pointer variable.
int i , j ;
printf(\n Enter Student Details: );
for( i=0 ; i<n ; i++)
{
ptr = &stu[i];
printf(\n Enter %d Students Details: ,i+1);
scanf(%s %d, ptrSname, &ptrSrollno);
for(j=0 ; j<6 ;j++)
{
int sum=0;
printf(\n Enter %d Subject marks: , j+1);
scanf(%d, &ptrres.marks[j]);//Accessing nested structure members through structure pointer.
sum=sum+ptrres.marks[j];
}
ptravg = sum/6.0;
}
for( i=0 ; i<n ; i++)
{
ptr = &stu[i];
printf(\n %d Students Details: ,i+1);
printf(\nName=%s \n Roll number = %d, ptrSname, ptrSrollno);
for(j=0 ; j<6 ;j++)
{
printf(\n %d Subject marks: %d , j+1,ptrres.marks[j]);
}
printf(\n Average marks of %d student is: %5.2f ,i+1,ptravg);
}
} // close of main function
GITAM UNIVERSITY

Page 16

OUTPUT:
Enter number of students: 1
Enter Student Details:
Enter 1 Students Details: Srikrishna 23
Enter 1 Subject marks: 86
Enter 2 Subject marks: 75
Enter 3 Subject marks: 69
Enter 4 Subject marks: 85
Enter 5 Subject marks: 96
Enter 6 Subject marks: 66
Student 1 Details:
Name = Srikrishna
Roll number = 23
1 subject marks: 86
2 subject marks: 75
3 subject marks: 69
4 subject marks: 85
5 subject marks: 96
6 subject marks: 66
Average marks of 1 student is: 79.500

// User INPUT

// Program output

1.8.4. Pointer with in Structures


Structure may contain the pointer variable as member. Pointers are used to store the address of memory
location. They can be de-referenced by * operator. Whenever we need to print the content of variable
pointed by some pointer, we have to dereference the pointer variable.
Example 8:
#include<stdio.h>
struct Student
{ int * ptr; // Stores address of integer variable
char * name ; // Stores address of Character Sting
}s1;
void main( )
{
int roll = 20;
s1.ptr = & roll;
s1.name = Srikrishna;
printf(\n Roll Number of Student : %d , *s1.ptr) ; /* We have stored the address of variable roll in
printf(\n Name of Student
: %s ,s1.name); a pointer member of structure thus we can
}
access value of pointer member directly using
de-reference operator. */
OUTPUT:
Roll Number of a Student: 20
Name of Student
: Srikrishna

GITAM UNIVERSITY

Page 17

1.9. Structures and Functions


A user define function can access the members of a structure in 3 ways.
i.
Passing individual structure members as parameters to a function.
ii.
Passing the entire structure by its name (pass by Value) to a function.
iii.
Passing the entire structure by its address (pass by Address) to a function.

1.9.1. Passing individual members of a structure


Example 9: Write a C program using structures to multiply two fractions and store product in another
fraction. Pass individual structure members as parameters to a function.
#include<stdio.h>
struct FRACTION
{
int num;
// num= numerator.
int denom; // denom= denominator.
};
int Multiply( int , int ); /*Function Declaration with 2 integer type formal parameters */
void main( )
{
struct FRACTION fr1,fr2,fr3; //three FRACTION structure variable declaration.
printf(\n Enter first fraction numerator and denominator: );
scanf(%d%d,&fr1.num,&fr1.denom);
printf(\n Enter second fraction numerator and denominator: );
scanf(%d%d,&fr2.num,&fr2.denom);
fr3.num
= Multiply( fr1.num , fr2.num);
fr3.denom = Multiply( fr1.denom , fr2.denom);

// Calling Multiply function

printf(\nThe Product is : %d / %d ,fr3.num,fr3.denom);


}
int Multiply( int a , int b ) //Multiply function definition
{
return ( a * b);
}
OUTPUT:
Enter first fraction numerator and denominator: 4 5
Enter second fraction numerator and denominator: 6 7
The Product is : 24 / 35

GITAM UNIVERSITY

Page 18

1.9.2. Passing the Entire Structure


Passing a structure is really no different from passing individual elements. Since the structure is a type,
we simply specify the type in the formal parameters of the called function. Similarly, the function can return a
structure. The same pass by value rules apply when we pass a structure to a function.
Example 10: Write a C program using structures to multiply two fractions and store product in another
fraction. Pass entire structure as parameters to a function.
#include<stdio.h>
typedef struct FRACTION
{
int num;
// num= numerator.
int denom; // denom= denominator.
};
FRACTION Multiply(FRACTION ,FRACTION ); /*Function Declaration with 2 FRACTION type
formal parameters & with FRACTION return type*/
void main( )
{
FRACTION fr1,fr2,fr3; //three FRACTION structure variable declaration.
printf(\n Enter first fraction numerator and denominator: );
scanf(%d%d,&fr1.num,&fr1.denom);
printf(\n Enter second fraction numerator and denominator: );
scanf(%d%d,&fr2.num,&fr2.denom);
fr3 = Multiply( fr1 , fr2 ); // Function Call passing 2 structure variables to function.
printf(\nThe Product is : %d / %d ,fr3.num,fr3.denom);
}
FRACTION Multiply( FRACTION ffr1 ,FRACTION ffr2 ) //Multiply function definition
{
FRACTION Rfr ;
Rfr.num = (ffr1.num) * (ffr2.num) ;
Rfr.denom = ( ffr1.denom) * (ffr2.denom) ;
return (Rfr) ; // returning
}
OUTPUT:
Enter first fraction numerator and denominator: 4 5
Enter second fraction numerator and denominator: 6 7
The Product is : 24 / 35

GITAM UNIVERSITY

Page 19

1.9.3. Passing structures through Pointers


Example 11: Write a C program using structures to multiply two fractions and store product in another
fraction. Pass structure variable address as parameters to a function.
#include<stdio.h>
typedef struct FRACTION
{
int num;
// num= numerator.
int denom; // denom= denominator.
};
FRACTION Multiply(FRACTION * ptr1 ,FRACTION * ptr2 );
/*Function Declaration with 2 FRACTION type
Pointer variable & with void return type*/
void main( )
{
FRACTION fr1,fr2,fr3; //three FRACTION structure variable declaration.
printf(\n Enter first fraction numerator and denominator: );
scanf(%d%d,&fr1.num,&fr1.denom);
printf(\n Enter second fraction numerator and denominator: );
scanf(%d%d,&fr2.num,&fr2.denom);
fr3 = Multiply( &fr1 , &fr2 ); // Function Call passing two structure variables address to function.
printf(\nThe Product is : %d / %d ,fr3.num,fr3.denom);
}
FRACTION Multiply( FRACTION * ptr1 ,FRACTION * ptr2 ) //Multiply function definition
{
FRACTION Rfr ;
Rfr.num = (ptr1num) * (ptr2num) ;
Rfr.denom = ( ptr1denom) * (ptr2denom) ;
return (Rfr) ; // returning
}
OUTPUT:
Enter first fraction numerator and denominator: 4 5
Enter second fraction numerator and denominator: 6 7
The Product is: 24 / 35

10. Self-Referential Structures


Self referential structures are those structures that contain a reference to data of its same type, i.e., in
addition to other data, a self referential structure contains a pointer to a data that is of the same type as that of
the structure. For example, consider the structure node given as follows.
struct node
{
int val;
struct node *next;
};

Self referential structure EXAMPLE

Self-referential structure is used in data structure such as binary tree, linked list, stack, Queue etc.
GITAM UNIVERSITY

Page 20

11. Review Question on Structures


1. What is nested structure? Write a program to print the details of employees of a organization
like (Name, DateOfJoin, Salary) using nested structures.
2. How many possible ways one can access the members of a structure using a structure variable
and a pointer to a structure variable? Illustrate with examples.
3. How to copy one structure to another structure of a same data type. Give an example
4. How can a entire structure be passed to a function? Explain with suitable examples.
5. What is the difference between structure and class? what is self referential structure.
6. Define a structure with the following three members: rollnumber, name, and total marks of a
student. Develop a C program for the above to read and display the details of a student.
7. Explain with examples about:
a. Self_ referential structure.
b. Nested structure.
8. Explain the memory allocation with a diagram,
for the following structure.
struct student
{
int rollno;
char name[10];
int total;
};
struct student x, y;
struct student a[10];
9. Define a structure in which, an integer, an array of characters, pointer to an array of integer and
another structure containing two integers are members. How do you access (i) Kth character of
the array (ii) second integer in the inner structure
10. Write a C program using nested structures to store the details of students?
11. Differentiate between unions and structures?
12. Define a structure data type called TimeStruct containing 3 members called hour,minute and
second. Develop a program that would assign values to the individual members and display the
time in the form 16:40:30.
13. Give an example to illustrate the concept of structures in C.
14. Write short notes on pointers to structures and pointers within Structures.
15. Write a program to illustrate the usage of pointers to structures?

GITAM UNIVERSITY

Page 21

UNIONS
INDEX
1. Introduction
1.1. Declaring a union
1.2. Initializing union
1.3. Accessing a member of a union
1.4. Array of union variables
1.5. Union inside structure
2. Typedef
3. Bit fields
4. Review questions

GITAM UNIVERSITY

Page 1

1. INTRODUCTION
A union is a user defined data type similar to structure. It is a collection of variables of different data
types. The only difference between a structure and a union is that in case of unions, memory is allocated
only to the biggest union member and all other members should share the same memory. In case of a
structure, memory is allocated to all the structure members individually. Thus unions are used to save
memory. They are useful for applications that involve multiple members, where values need not be assigned
to all the members at any one time.

1.1. Declaring a union


The syntax for declaration a union is the same as that of declaring a structure. The only difference is
that instead of using the keyword struct, the keyword union would be used.
union Identifier
{
data_type var_name;
data_type var_name;
. . . . . . . . . . . . .;
}union variable;

union POINT
{
int a;
float b;
char c;
}pont1;

SYNTAX

EXAMPLE

Memory allocation representation


2 bytes

float

4 bytes
1 byte

1byte 2 byte 3 byte 4 byte

int

char
int

char
float

Memory allocation in structure

Memory allocation in union

Union variable declaration


Union variable can be declared as same as declaration of structure variable. We can declare a
union variable with global declaration or with local declaration.
union POINT
{
int a;
float b;
char c;
}point1,point2;

union POINT
{
int a;
float b;
char c;
}point1,point2;

void main( )
{
.....
}

void main( )
{
union POINT point1,point2;
.........
}

Global declaration of union variable

GITAM UNIVERSITY

Local declaration of union variable

Page 2

1.2. Initializing union


Initialization of a union variable is similar like initialization of structure a structure variable. Only
one different is in the allocation of memory size. A union members share the same memory space, so fresh
data replaces any existing data.
Example 13: Write a C program to illustrate initialization of union variable .
#include<stdio.h>
typedef struct POINT1
{
int x; int y;
};
typedef union POINT2
{
int x; int y;
};
void main( )
{
POINT1 P1; POINT2 P2;
P2.x = 4; P2.y = 5;
printf(\n The co-ordinates of point P1are %d and %d ,P1.x , P1.y);
printf(\n The co-ordinates of point P2 are %d and %d ,P2.x , P2.y);
}
OUTPUT:
The co-ordinates of point P1are 2 and 3
The co-ordinates of point P1are 5 and 5

NOTE:
1. It is an error to initialize any other union member except the first member.
2. The size of a union is equal to the size of its largest member.
Example 14:
#include<stdio.h>
typedef struct POINT1
{ int x; double y; };
typedef union POINT2
{ int x;
double y; };

size of int data type is 4


bytes.

size of double data type is


8 bytes.

void main( )
{
POINT1 P1; POINT2 P2;
printf(\n The size of Structure Variable P1 is: %d bytes,sizeof(P1));
printf(\n The size of Union Variable P2 is: %d bytes,sizeof(P2));
}
OUTPUT:
The size of Structure Variable P1 is: 12 bytes
The size of Structure Variable P1 is: 8 bytes

GITAM UNIVERSITY

Page 3

1.3. Accessing a member of a union


Accessing members of a union variable will be done by using dot operator (

) and arrow operator ().

Example 15:
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
void main( )
Here, we can see that values of i and f members of
{
union got corrupted because final value assigned to the
union Data data;
variable has occupied the memory location and this is
data.i = 10;
the reason that the value if str member is getting
data.f = 220.5;
printed very well. Now let's look into the same
strcpy( data.str, "C Programming");
example once again where we will use one variable at
printf( "data.i : %d\n", data.i);
a time which is the main purpose of having union:
printf( "data.f : %f\n", data.f);
printf( "data.str : %s\n", data.str);
}
OUTPUT:
data.i : 1917853763
data.f : 4122360580327794860452759994368.000000
data.str : C Programming
Example 16:
#include <stdio.h>
#include <string.h>
union Data
{
int i; float f; char str[20];
};
void main( )
{
union Data data;
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
strcpy( data.str, "C Programming");
printf( "data.str : %s\n", data.str);
}
OUTPUT:
data.i : 10
data.f : 220.500000
data.str : C Programming

GITAM UNIVERSITY

Here, all the members are getting printed very well


because one member is being used at a time.

Page 4

1.4. Array of union variables


Like structures we can also have an array of union variables. However, because of the problem of
new data overwriting existing data in the other fields, the program may not display the accurate result.
Example 17:
#include<stdio.h>
union POINT
{
int x,y;
};
void main( )
{
int i;
union POINT points[3];
points[0].x = 2; points[0].y = 5;
points[1].x = 4; points[1].y = 7;
points[2].x = 9; points[2].y = 3;
for( i=0;i<3;i++)
{
printf(\n Co-ordinates of Point[%d] are %d and %d, i, points[i].x, points[i].y );
}
}
OUTPUT:
Co-ordinates of Point[0] are 5 and 5
Co-ordinates of Point[1] are 7 and 7
Co-ordinates of Point[2] are 3 and 3

1.5. Union inside structure


Unions can be very useful when declared inside a structure. Consider below example which
illustrates such a scenario.
Example 18:
#include<stdio.h>
struct STUDENT
{
union
{ char name[25];
Int roll_no;
};
float avg;
};
void main( )
{
struct STUDENT stu1;
char choice;
printf(\n Enter student name or roll number: );
printf(\n Do you want to enter the name? (Y or N): );
scanf(%c,&choice);

GITAM UNIVERSITY

Page 5

if(choice == Y || choice == y )
{
printf(\n Enter the name: );
scanf(%s,&stu1.name);
}
else
{
printf(\n Enter the Roll number: );
scanf(%d,&stu1.roll_no);
}
printf(\n Enter the marks average: );
scanf(%f,&stu1.avg);
printf(\n****** ENTERED DETAILS******)
if(choice == Y || choice== y)
{
printf(\n Name: %s,stu1.name);
}
else
{
printf(\n Roll Number: %d,stu1.roll_no);
}
printf(\n Marks Average : %f , stu1.avg);
} // close of main
OUTPUT:
Enter student name or roll number:
Do you want to enter the name? (Y or N): N
Enter the Roll number: 45
Enter the marks average: 68
****** ENTERED DETAILS******
Roll Number: 45
Marks Average : 68.00000

// User Input

// Program Output

NOTE: Pointing to unions, passing to functions, and passing pointers to unions to functions are all done
in the same way as that of structure.

2. typedef keyword
A typedef declaration lets you define your own identifiers that can be used in place of basic data type
such as int, float, and double. A typedef declaration does not reserve storage. The names you define using
typedef are not new data types, but synonyms for the data types or combinations of data types they
represent.
Example 19:
#include<stdio.h>
void main( )
{
typedef int India;
India a=10, b=15;
printf(SUM OF %d and %d is : %d,a,b,(a+b));
}

GITAM UNIVERSITY

OUTPUT:
SUM OF 10 and 15 is: 25

Page 6

3. BIT FIELDS
Suppose your C program contains a number of TRUE/FALSE variables grouped in a structure calledstatus,
as follows:
struct
{
unsigned int widthValidated;
unsigned int heightValidated;
} status;
This structure requires 8 bytes of memory space but in actual we are going to store either 0 or 1 in each of
the variables. The C programming language offers a better way to utilize the memory space in such
situation. If you are using such variables inside a structure then you can define the width of a variable which
tells the C compiler that you are going to use only that number of bytes. For example, above structure can be
re-written as follows:
struct
{
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status;
Now, the above structure will require 4 bytes of memory space for status variable but only 2 bits will be
used to store the values. If you will use up to 32 variables each one with a width of 1 bit , then also status
structure will use 4 bytes, but as soon as you will have 33 variables, then it will allocate next slot of the
memory and it will start using 8 bytes. Let us check the following example to understand the concept:
#include <stdio.h>
#include <string.h>
/* define simple structure */
struct
{
unsigned int widthValidated;
unsigned int heightValidated;
} status1;
/* define a structure with bit fields */
struct
{
unsigned int widthValidated : 1;
unsigned int heightValidated : 1;
} status2;
int main( )
{
printf( "Memory size occupied by status1 : %d\n", sizeof(status1));
printf( "Memory size occupied by status2 : %d\n", sizeof(status2));
return 0;
}
Memory size occupied by status1 : 8
Memory size occupied by status2 : 4

GITAM UNIVERSITY

Page 7

Bit Field Declaration


The declaration of a bit-field has the form inside a structure:
struct
{
type [member_name] : width ;
};
Below the description of variable elements of a bit field:
Elements

Description

Type

An integer type that determines how the bit-field's value is


interpreted. The type may be int, signed int, unsigned int.

member_name

The name of the bit-field.

Width

The number of bits in the bit-field. The width must be less than or
equal to the bit width of the specified type.

The variables defined with a predefined width are called bit fields. A bit field can hold more than a single
bit for example if you need a variable to store a value from 0 to 7 only then you can define a bit field with a
width of 3 bits as follows:
struct
{
unsigned int age : 3;
} Age;
The above structure definition instructs C compiler that age variable is going to use only 3 bits to store the
value, if you will try to use more than 3 bits then it will not allow you to do so. Let us try the following
example:
#include <stdio.h>
#include <string.h>
struct
{
unsigned int age : 3;
} Age;
int main( )
{
Age.age = 4;
printf( "Sizeof( Age ) : %d", sizeof(Age) );
printf( "Age.age : %4d\n", Age.age );
Age.age = 7;
printf( "Age.age : %d\n", Age.age );
Age.age = 8;
printf( "Age.age : %d\n", Age.age );
return 0;
}
Sizeof( Age ) : 4 Age.age : 4
Age.age : 7
Age.age : 0

GITAM UNIVERSITY

Page 8

4. REVIEW QUESTIONS
1.
2.
3.
4.
5.
6.
7.

What is a Union in C? How data is stored using Union?


What are the advantages of union?
Differentiate between unions and structures?
Explain bit field operators with an example?
What are the operations on unions?
Distinguish between union and structure. Give their application areas.
How does it differ from a structure? For what kinds of applications unions are
useful?

THE - END

GITAM UNIVERSITY

Page 9

You might also like