Module 5 Structures Unions Enumerated DT Files
Module 5 Structures Unions Enumerated DT Files
Structure, Union, and Enumerated Data Type: Introduction, structures and functions, Unions,
unions inside structures, Enumerated data type.
Files: Introduction to files, using files in C, reading and writing data files. , Detecting end of file
Textbook: Chapter 15.1 – 15.10, 16.1-16.5
STRUCTURES
Definition
m
Structures is a user defined data type which is a collection of related heterogeneous
data under a single name
A structure is a collection of data members grouped together under a single name. It
provides an elegant and powerful way for keeping related data together.
co
A structure contains an ordered group of data objects. Unlike the elements of an array, the
data objects within a structure can have varied and different data types.
Structures are basically used to store ‘Records’ in memory through C language
Examples:
Student record: student id, name, major, gender, start year, …
e.
Bank account: account number, name, currency, balance, …
Address book: name, address, telephone number, …
Syntax and Example for Structure declaration
General Format/Syntax of a Structure
dg
A structure is declared using the keyword ‘struct’ followed by the structure name.
All the data members of the structure are declared within the structure
A structure type is generally declared by using the following syntax:
struct struct_name
{
ue
datatype member1;
datatype member2;
…..
datatype member_n;
};
Example
vt
m
struct date
{
int day;
int month;
co
int year;
};
struct student
{
char name[20];
int rno;
char collegename[20];
float score;
} s1,s2;
Here s1 and s2 are called as structure variables
Example:
struct student Student1, Student2;
Here, Student1 and Student2 are called as structure variables
typedef declarations:
The typedef keyword enables the programmer to create a new data type name from
an existing data type name from existing data type.
The syntax of using typedef is as follows:
typedef existing_datatype new_datatype;
m
Example:
typedef struct student
{
char name[50];
char branch[50];
co
int ID_no;
} STUD;
Now, since the structures name is preceeded with typedef keyword, STUD becomes
new data type. Hence variables can be declared using the following statement
e.
STUD st1, st2, st3;
Initialization of Structures:
dg
…..
datatype member_n;
}struct_var = {constant1,constant2,..constantn};
OR
struct struct_name
vt
{
datatype member1;
datatype member2;
…..
datatype member_n;
};
int month;
int year;
}D = {12,07,2000};
OR
struct date
{
int day;
int month;
int year;
};
m
struct date D = {10,7,1990};
co
The members of a struct type variable are accessed with the dot (.) operator:
<struct-variable> . <member_name>;
The dot(.) operator is used to select a particular member of the structure.
e.
For example:
To assign the value 12345 as Id member of Student1 variable, we need use the
following instruction
Student1.Id = 12345;
dg
Example:
Student1.Name = "Chan Tai Man";
Student1.Id = 12345;
Student1.Dept = "COMPUTER”;
Student1.gender = 'M';
Student2 = Student1;
o COMPARING
Pavithra B,AP,Dept. of CSE(DS),SVIT
Structures,Unions,Enumeration
o The variables of the structures are not allowed to compare directly, whereas
the individual data members can be compared.
o An error will be generated when two variables of a structure are compared
o For example,
if(Student1 == Student2)
This instruction will result in an error, as C language doesn’t allow the user to
compare two variables
o For example, the department of two students can be compared using the
instruction
if(Student1.Dept == Student2.Dept)
m
Here, the department of the students are compared.
co
There are three ways to find the size of the structure, namely:
1. Adding the size of the data members(Simple Addition)
2. Using sizeof() operator
3. Subtracting the addresses
e.
1. Simple Addition
In this method, the size of all the data members are added to find the size of the
dg
entire structure.
For example, consider the following structure;
struct student
{
char name[20];
int rno;
ue
char collegename[20];
float score;
};
Now,
vt
The entire structure takes 46bytes memory to store one record of information
Further, if we declare variables to the structure, each variable occupies 46 bytes of
memory
i.e.,
struct student S1,S2,S3;
Here, S1 takes 46bytes, S2 takes 46bytes and S3 takes 46bytes of memory
Pavithra B,AP,Dept. of CSE(DS),SVIT
Structures,Unions,Enumeration
m
char collegename[20];
float score;
};
To know the size of the structure student, we can use the following instruction
co
size = sizeof(student);
Now, the variable size holds the value 46 as answer
Also, sizAlso, sizeof() operator can be used for variables declared to the structure,
i.e.,
e.
struct student S1;
size = sizeof(S1);
dg
Here, the size holds the value 46 as an answer
3. Subtracting the Addresses
This method is used when the variable declared to structure is an array
To find the size of the structure, we subtract the address of the first element of the
next consecutive variable from the address of the first element of preceding
ue
structure variable.
For example,
struct student
{
int rno;
vt
char name[20];
char collegename[20];
float score;
}S[10];
The following method finds the size of each variable
int start,end;
start = &S[0].rno;
end = &S[1].rno;
Nested Structures
m
char mid_name[20];
char last_name[20];
};
typedef struct
{
co
int dd;
int mm;
int yy;
}DATE;
typedef struct student
e.
{
int rno;
NAME Sname;
dg
char course[20];
DATE dob;
float fee;
};
In the above example, the structure student contains two other structures NAME
ue
and DATE as its members, hence following the nested structures concept
To assign values to the members of the structure, we use
Array of Structures
An array whose elements are of type structure is called array of structure.
It is generally useful when we need multiple structure variables in our program.
Pavithra B,AP,Dept. of CSE(DS),SVIT
Structures,Unions,Enumeration
So, if we declare the variable this way, it’s not possible to handle this.
struct Employee emp1, emp2, emp3, .. . ... . .. ... emp1000;
For that, we can define an array whose data type will be struct Employee
m
so that will be easily manageable.
Syntax for Declaration of Array of Structures
struct structure_name array_name [number_of_elements];
Example
co
struct student S[100];
Syntax for Initialization of Array of Structures
e. We can initialize the array of structures in the following ways:
......
......
};
The same initialization can also be done as:
ue
};
Example for initialization of array of structures
typedef struct student
{
int rno;
char name[20];
char course[20];
float fee;
};
struct student S[2] = { {123,”Raju”,”CSE”,100000},
{124,”Padma”,”ISE”,100000}};
m
1. Passing individual Members
To pass any individual member of the structure to a function we must use the direct
selection to refer to the individual member
co
For example
#include <string.h>
#include<stdio.h>
struct student
e.
{
int id;
char name[20];
float percentage;
dg
};
int main()
{
struct student record;
vt
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
}
OUTPUT:
Id is : 1
In this program, the whole structure is passed to another function by value. It means
the whole structure is passed to another function with all members and their values.
So, this structure can be accessed from called function. This concept is very useful
while writing very big programs in C
Example
#include <string.h>
#include<stdio.h>
struct student
{
int id;
m
char name[20];
float percentage;
};
co
void display(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
e.
}
int main()
{
dg
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
ue
display(record);
return 0;
}
OUTPUT:
vt
Id is: 1
Name is: Raju
Percentage is: 86.500000
Example
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
m
void func(struct student *record)
{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
co
printf(" Percentage is: %f \n", record->percentage);
}
int main()
{
e.
struct student record;
record.id=1;
strcpy(record.name, "Raju");
dg
record.percentage = 86.5;
func(&record);
return 0;
}
ue
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
vt
Self-Referential Structures
Self Referential structures are those structures that have one or more pointers
which point to the same type of structure, as their member.
In other words, structures pointing to the same type of structures are self-
referential in nature
Example:
m
struct node
{
int data1;
char data2;
co
struct node* link;
};
int main()
{
e. struct node ob;
return 0;
}
In the above example ‘link’ is a pointer to a structure of type ‘node’. Hence, the
dg
UNIONS
ue
Definition:
The Union is a user-defined data type in C language that can contain heterogeneous data
elements under a single name
Size of Union
vt
The size of the union will always be equal to the size of the largest member of the
array. All the less-sized elements can store the data in the same space without any
overflow.
Syntax for Declaring a Union
union union_name
{
datatype member1;
datatype member2;
...
datatype membern;
}var1,var2;
Example
Pavithra B,AP,Dept. of CSE(DS),SVIT
Structures,Unions,Enumeration
union test1
{
int x;
int y;
float z;
}T1,T2;
Syntax for initializing unions
union union_name
{
m
datatype member1;
datatype member2;
...
co
datatype membern;
}var1 = {constant1,constant2,….,constantn};
Arrays of Unions
When we have huge data to store, in spite of creating scalar variables we can declare the
ue
float z;
}T[10];
int main()
{
int i;
T[0].x = 10;
T[0].y = 20;
T[0].z = 1.5;
T[1].x = 100;
T[1].y = 200;
T[1].z =2.5;
for(i=0;i<=2;i++)
printf(“T[i].x = %d,T[i].y = %d,T[i].z = %f\n”,T[i].x,T[i].y,T[i].z);
Pavithra B,AP,Dept. of CSE(DS),SVIT
Structures,Unions,Enumeration
}
OUTPUT:
T[i].x = 10,T[i].y = 20,T[i].z = 1.5
T[i].x = 100,T[i].y = 200,T[i].z = 2.5
m
The structure can contain data in multiple Only one member can contain data at the
members at the same time. same time.
It is declared using the struct keyword. It is declared using the union keyword.
Syntax: Syntax:
struct tag_name union tag_name
co
{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };
e.
We can access all members of structure at We can access only one member of union
a time. at a time.
Structure occupies higher memory space. Union occupies lower memory space over
structure.
dg
Structure allocates storage space for all its Union allocates one common storage space
members separately. for all its members.
All the members are active at any given Only the member that access the memory is
point of time active at any given point of time
Memory is not shared among data members Memory is shared among the data members
ue
EUMERATED DATATYPES
Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names
vt
to Definition
integral constants, the names make a program easy to read and maintain.
Syntax for enum declaration
Example
enum State {Working = 1, Failed = 0};
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec};
Variables
Variables of type enum can also be defined. They can be defined in two ways:
Pavithra B,AP,Dept. of CSE(DS),SVIT
Structures,Unions,Enumeration
// Or
Initialization of Enum
1. Two enum names can have same value. For example, in the following C program
m
both ‘Failed’ and ‘Freezed’ have same value 0.
#include <stdio.h>
enum State {Working = 1, Failed = 0, Freezed = 0};
co
int main()
{
printf("%d, %d, %d", Working, Failed, Freezed);
return 0;
}
e.
Output:
1, 0, 0
If we do not explicitly assign values to enum names, the compiler by default assigns
dg
values starting from 0. For example, in the following C program, sunday gets value
0, monday gets 1, and so on.
#include <stdio.h>
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};
ue
int main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
return 0;
}
vt
Output:
int main()
{
1 2 5 6 10 11 12
The value assigned to enum names must be some integral constant, i.e., the value
must be in range from minimum possible integer value to maximum possible
integer value.
m
co
e.
dg
ue
vt