Professional Documents
Culture Documents
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
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
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.
GITAM UNIVERSITY
Page 2
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.
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( )
{
...........;
...........;
}
typedef struct
{
char Sname[20];
int
Srollnumber;
int
Sclass;
double
Sphonenumber;
}STUDENT;
main( )
{
struct STUDENT stu1,stu2;
..............;
. . . . . . . . . . . . . .;
}
main( )
{
STUDENT stu1,stu2;
. . . . . . . . . . . . .;
. . . . . . . . . . . . .;
}
GITAM UNIVERSITY
Page 4
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.
GITAM UNIVERSITY
Page 5
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:
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
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
GITAM UNIVERSITY
Page 9
GITAM UNIVERSITY
// 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
GITAM UNIVERSITY
typedef struct
{
int seconds;
int minutes;
int hours;
}TIME;
Low Level Structure2
typedef struct
{
DATE date;
TIME time;
}STAMP;
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
void main( )
{ . . . . . .;
. . . . . .;
}
GITAM UNIVERSITY
Page 14
GITAM UNIVERSITY
Page 15
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
GITAM UNIVERSITY
Page 17
GITAM UNIVERSITY
Page 18
GITAM UNIVERSITY
Page 19
Self-referential structure is used in data structure such as binary tree, linked list, stack, Queue etc.
GITAM UNIVERSITY
Page 20
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.
union POINT
{
int a;
float b;
char c;
}pont1;
SYNTAX
EXAMPLE
float
4 bytes
1 byte
int
char
int
char
float
union POINT
{
int a;
float b;
char c;
}point1,point2;
void main( )
{
.....
}
void main( )
{
union POINT point1,point2;
.........
}
GITAM UNIVERSITY
Page 2
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; };
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
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
Page 4
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
Description
Type
member_name
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.
THE - END
GITAM UNIVERSITY
Page 9