0% found this document useful (0 votes)
2 views

Module 5 Structures Unions Enumerated DT Files

The document provides an overview of structures, unions, and enumerated data types in C programming, detailing their definitions, syntax, and usage. It explains how to declare and initialize structures, access their members, and the concept of nested structures and arrays of structures. Additionally, it covers the interaction of structures with functions and methods for determining the size of structures.

Uploaded by

sidhubuyya3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module 5 Structures Unions Enumerated DT Files

The document provides an overview of structures, unions, and enumerated data types in C programming, detailing their definitions, syntax, and usage. It explains how to declare and initialize structures, access their members, and the concept of nested structures and arrays of structures. Additionally, it covers the interaction of structures with functions and methods for determining the size of structures.

Uploaded by

sidhubuyya3
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Structures,Unions,Enumeration

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

 Declare a structure to store information about a student


struct student
{
char name[20];
int rno;
char college[20];
};
 Declare a structure to store information about a point in the co-ordinate system
struct point
{
int x,y;
};
Pavithra B,AP,Dept. of CSE(DS),SVIT
Structures,Unions,Enumeration

 Declare a structure to store Customer information


struct customer
{
int cust_id;
char cust_name[30];
char address[100];
long int phone_num;
float salary;
};

 Declare a structure to store information of a particular date

m
struct date
{
int day;
int month;

co
int year;
};

 Structures: Basic Points


 Individual components of a struct type are called members (or fields).
e.
 Members can be of different types (simple, array or struct or any basic type).
 A struct is named as a whole while individual members are named using field
identifiers.
dg
 Complex data structures can be formed by defining arrays of structs
 Memory will not be allocated to the any of the members when structure is declared
 it gives a template that conveys to the C compiler how the structure should be laid
out in memory and gives details of the member names.
 Memory will be allocated only when the variable is declared
ue

 What is Structure Variable?


A variable which is used to access the members of the structure
 Variables are used to initialize the members of the structure

 Declaring Structure Variable


vt

struct student
{
char name[20];
int rno;
char collegename[20];
float score;
} s1,s2;
Here s1 and s2 are called as structure variables

 Variables can be declared outside the Structure Definition also, like:

struct struct_name var1,var2,….varn;

Pavithra B,AP,Dept. of CSE(DS),SVIT


Structures,Unions,Enumeration

 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

 Initializing a structure means assigning some constants to the members of the


structure
struct struct_name
{
datatype member1;
datatype member2;
ue

…..
datatype member_n;
}struct_var = {constant1,constant2,..constantn};

OR
struct struct_name
vt

{
datatype member1;
datatype member2;
…..
datatype member_n;
};

struct struct_name struct_var = {constant1, constant2,…,constantn};


 Example for Structure Initialization:
struct date
{
int day;
Pavithra B,AP,Dept. of CSE(DS),SVIT
Structures,Unions,Enumeration

int month;
int year;
}D = {12,07,2000};

OR
struct date
{
int day;
int month;
int year;
};

m
struct date D = {10,7,1990};

 Accessing Structure Members

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

Likewise, to assign name, department and gender to the respective members, we


use the following instructions:
Student1.Name = "Chan Tai Man";
Student1.Dept = "COMPUTER”;
Student1.gender = 'M';
ue

 Copying and Comparing Structures OR struct-to-struct assignment


 COPYING
The values contained in one struct type variable can be assigned to another variable
of the same struct type.
vt

Example:
Student1.Name = "Chan Tai Man";
Student1.Id = 12345;
Student1.Dept = "COMPUTER”;
Student1.gender = 'M';
Student2 = Student1;

The variable Student2 will have the values as Student1 have.

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.

 Finding the size of Structure

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

size = size of name + size of rno + size of collegename + size of float


i.e.,
size = 20 + 2 + 20 + 4
size = 46 bytes

 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

So totally, they take 138 bytes of memory for 3 variables

2. Using sizeof() operator


 sizeof() operator when used, returns the total memory reserved for the structure in
bytes
 For example
struct student
{
char name[20];
int rno;

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;

size = end - start;

size holds the value as 46

Pavithra B,AP,Dept. of CSE(DS),SVIT


Structures,Unions,Enumeration

 Nested Structures

 A nested structure in C is a structure within structure.


 One structure can be declared inside another structure in the same way structure
members are declared inside a structure.
 For example
typedef struct NAME
{
char first_name[20];

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

student . Sname . first_name = “Surya”;


student . Sname . mid_name = “Raj” ;
vt

student . Sname . last_name = “Kiran” ;


student . dob. dd = 10;
student . dob . mm = 2;
student . dob . yy = 1990;
student . course = “Computer Science”;
student . rno = 1234;
student . fee = 80000;

 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

 Need for Array of Structures


 Suppose we have 50 employees and we need to store the data of 50
employees. So for that, we need to define 50 variables of struct Employee
type and store the data within that. However, declaring and handling the 50
variables is not an easy task. Let’s imagine a bigger scenario, like 1000
employees.

 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:

struct structure_name array_name [number_of_elements] = {


{element1_value1, element1_value2, ....},
{element2_value1, element2_value2, ....},
dg

......
......
};
 The same initialization can also be done as:
ue

struct structure_name array_name [number_of_elements] = {


element1_value1, element1_value2 ....,
element2_value1, element2_value2 .....
vt

};
 Example for initialization of array of structures
typedef struct student
{
int rno;
char name[20];
char course[20];
float fee;

Pavithra B,AP,Dept. of CSE(DS),SVIT


Structures,Unions,Enumeration

};
struct student S[2] = { {123,”Raju”,”CSE”,100000},
{124,”Padma”,”ISE”,100000}};

 Structures and Functions


 A function may access the members of a structure in three ways as follows
1. Passing individual members
2. Passing the entire structures
3. Passing the address of the structure

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

};

void func(int id)


{
printf(" Id is: %d \n", id);
ue

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

2. Passing the entire structure

Pavithra B,AP,Dept. of CSE(DS),SVIT


Structures,Unions,Enumeration

 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

struct student record;

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

3. Passing Structures through Pointers


 In this program, the whole structure is passed to another function by address. It
means only the address of the structure is passed to another function. The whole
structure is not passed to another function with all members and their values. So,
this structure can be accessed from called function by its address.
 When pointrs are used in structures, the “pointing-to” operator is used to access the
members of the structure
 The symbol “->” is used as pointing-to operator
Pavithra B,AP,Dept. of CSE(DS),SVIT
Structures,Unions,Enumeration

 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

Pavithra B,AP,Dept. of CSE(DS),SVIT


Structures,Unions,Enumeration

 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

structure ‘node’ is a self-referential structure with ‘link’ as the referencing pointer.

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};

 Example for initializing unions


e.
union test1
{
int x;
dg
int y;
float z;
}T1 = {10,20,60.5};

 Arrays of Unions
When we have huge data to store, in spite of creating scalar variables we can declare the
ue

variable as an array to store the related information


union test1
{
int x;
int y;
vt

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

 Difference between Structures and Unions


Structure Union
The size of the structure is equal to or The size of the union is the size of its
greater than the total size of all of its largest member.
members.

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

enum enumeration_name{identifier1, identifier2, identifier3, ....... };

 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

enum week{Mon, Tue, Wed};


enum week day;

// Or

enum week{Mon, Tue, Wed}day;

Here, day is called as the variables of enum type week

 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:

The day number stored in d is 4


 We can assign values to some name in any order. All unassigned names get value
as value of previous name plus one.
#include <stdio.h>
enum day {sunday = 1, monday, tuesday = 5,wednesday, thursday = 10, friday,
saturday};

int main()
{

Pavithra B,AP,Dept. of CSE(DS),SVIT


Structures,Unions,Enumeration

printf("%d %d %d %d %d %d %d", sunday, monday, tuesday, wednesday,


thursday, friday, saturday);
return 0;
}
Output:

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

Pavithra B,AP,Dept. of CSE(DS),SVIT

You might also like