Download as pdf or txt
Download as pdf or txt
You are on page 1of 127

Unit-8: Structure and Union

8.1 Introduction to Structure


8.2 Declaring and Defining Structures
8.3 Accessing Structure member
8.4 Introduction to Nested Structure
8.5 Arrays of Structures
8.6 Union: Declaring and defining Union,
Accessing Union member
8.7 Difference between Structure and Union
8.1 Introduction to Structure
A structure is a user defined data type in C/C++. A structure creates a data
type that can be used to group items of possibly different types into a single
type.
Arrays allow to define types of variables that can hold several data items of
the same kind. Structures are used to represent a record.

8.2 Declaring and Defining Structures

struct keyword is used to create a structure.


Example:
struct address
{
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

A structure variable can either be declared with structure declaration or as a separate


declaration like basic types.

// A variable declaration with structure declaration.


struct Point
{
int x, y;
} p1; // The variable p1 is declared with 'Point'

// A variable declaration like basic data types


struct Point
{
int x, y;
};

int main()
{
struct Point p1; // The variable p1 is declared like a normal variable
}
How to initialize structure members?
Structure members cannot be initialized with declaration.

struct Point
{
int x = 0; // COMPILER ERROR: cannot initialize members here
int y = 0; // COMPILER ERROR: cannot initialize members here
};

The reason for the above error is simple: when a data type is declared, no
memory is allocated for it. Memory is allocated only when variables are
created.
Structure members can be initialized using curly braces ‘{}’. For example, the
following is a valid initialization.
struct Point
{
int x, y;
};

int main()
{
// A valid initialization. member x gets value 0 and y
// gets value 1. The order of declaration is followed.
struct Point p1 = {0, 1};
}
8.3 Accessing Structure member
Structure members are accessed using dot (.) operator.
#include<stdio.h>

struct Point
{
int x, y;
};

int main()
{
struct Point p1 = {0, 1};

// Accessing members of point p1


p1.x = 20;
printf ("x = %d, y = %d", p1.x, p1.y);

return 0;
}

Limitations Of C Structure:
1. No Data Hiding: C Structures do not permit data hiding. Structure
members can be accessed by any function, anywhere in the scope of
the Structure.
2. Functions inside Structure: C structures do not permit functions
inside Structure
3. Static Members: C Structures cannot have static members inside their
body
4. Access Modifiers: C Programming language does not support access
modifiers. So they cannot be used in C Structures.
5. Construction creation in Structure: Structures in C cannot have
constructor inside Structures.

8.4 Introduction to Nested Structure


When a structure contains another structure, it is called a nested structure. For
example,we have two structures named Address and Employee. To make Address
nested to Employee, we have to define Address structure before and outside
Employee structure and create an object of Address structure inside Employee
structure.

struct structure1
{
----------
----------
};

struct structure2
{
----------
----------
struct structure1 obj;
};

Example for structure within structure or nested structure

#include<stdio.h>

struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};

struct Employee
{
int Id;
char Name[25];
float Salary;
struct Address Add;
};

void main()
{
int i;
struct Employee E;

printf("\n\tEnter Employee Id : ");


scanf("%d",&E.Id);

printf("\n\tEnter Employee Name : ");


scanf("%s",&E.Name);
printf("\n\tEnter Employee Salary : ");
scanf("%f",&E.Salary);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.HouseNo);

printf("\n\tEnter Employee City : ");


scanf("%s",&E.Add.City);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.PinCode);

printf("\nDetails of Employees");
printf("\n\tEmployee Id : %d",E.Id);
printf("\n\tEmployee Name : %s",E.Name);
printf("\n\tEmployee Salary : %f",E.Salary);
printf("\n\tEmployee House No : %s",E.Add.HouseNo);
printf("\n\tEmployee City : %s",E.Add.City);
printf("\n\tEmployee House No : %s",E.Add.PinCode);

}
Output :
Enter Employee Id : 101
Enter Employee Name : Suresh
Enter Employee Salary : 45000
Enter Employee House No : 4598/D
Enter Employee City : Delhi
Enter Employee Pin Code : 110056

Details of Employees
Employee Id : 101
Employee Name : Suresh
Employee Salary : 45000
Employee House No : 4598/D
Employee City : Delhi
Employee Pin Code : 110056

8.5 Arrays of Structures


An array of structures in C can be defined as the collection of multiple structure
variables where each variable contains information about different entities. The array
of structures in C are used to store information about multiple entities of different
data types. The array of structures is also known as the collection of structures.

Let's see an example of an array of structures that stores information of 5 students


and prints it.
#include<stdio.h>
#include <string.h>
struct student{
int rollno;
char name[10];
};
int main(){
int i;
struct student st[5];
printf("Enter Records of 5 students");
for(i=0;i<5;i++){
printf("\nEnter Rollno:");
scanf("%d",&st[i].rollno);
printf("\nEnter Name:");
scanf("%s",&st[i].name);
}
printf("\nStudent Information List:");
for(i=0;i<5;i++){
printf("\nRollno:%d, Name:%s",st[i].rollno,st[i].name);
}
return 0;
}
Output:
Enter Records of 5 students
Enter Rollno:1
Enter Name:Sonoo
Enter Rollno:2
Enter Name:Ratan
Enter Rollno:3
Enter Name:Vimal
Enter Rollno:4
Enter Name:James
Enter Rollno:5
Enter Name:Sarfraz

Student Information List:


Rollno:1, Name:Sonoo
Rollno:2, Name:Ratan
Rollno:3, Name:Vimal
Rollno:4, Name:James
Rollno:5, Name:Sarfraz

8.6 Union: Declaring and defining Union, Accessing Union


member
Union can be defined as a user-defined data type which is a collection of different
variables of different data types in the same memory location. The union can also be
defined as many members, but only one member can contain a value at a particular
point in time.

Union is a user-defined data type, but unlike structures, they share the same memory
location.

In union, members will share the memory location. If we try to make changes in any
of the members then it will be reflected to the other member as well. Let's
understand this concept through an example.

union abc
{
int a;
char b;
}var;
int main()
{
var.a = 66;
printf("\n a = %d", var.a);
printf("\n b = %d", var.b);

In the above code, the union has two members, i.e., 'a' and 'b'. The 'var' is a variable of
union abc type. In the main() method, we assign the 66 to 'a' variable, so var.a will
print 66 on the screen. Since both 'a' and 'b' share the memory location, var.b will
print 'B' (ascii code of 66).

Deciding the size of the union

The size of the union is based on the size of the largest member of the union.

union abc{
int a;
char b;
float c;
double d;
};
int main()
{
printf("Size of union abc is %d", sizeof(union abc));
return 0;
}
As we know, the size of int is 4 bytes, size of char is 1 byte, size of float is 4 bytes, and the
size of double is 8 bytes. Since the double variable occupies the largest memory among all
the four variables, 8 bytes will be allocated in the memory. Therefore, the output of the above
program would be 8 bytes.

Accessing members of union using pointers


We can access the members of the union through pointers by using the (->) arrow operator.
Let's understand through an example.
#include <stdio.h>
union abc
{
int a;
char b;
};
int main()
{
union abc *ptr; // pointer variable declaration
union abc var;
var.a= 90;
ptr = &var;
printf("The value of a is : %d", ptr->a);
return 0;
}
In the above code, we have created a pointer variable, i.e., *ptr, that stores the address of
var variable. Now, ptr can access the variable 'a' by using the (->) operator. Hence the output
of the above code would be 90.

8.7 Difference between Structure and Union


Unit:9 Files and Files Handling in ‘C’:
9.1 Introduction to data file
9.2 Opening and closing sequential files
9.3 Modes of opening file (r, w, a)
9.4 Processing file
9.1 Introduction to data file
A collection of data which is stored on a secondary device like a hard disk is known
as a file.
A file is generally used in real-life applications that contain a large amount of data.

9.2 Opening and closing sequential files

Opening a file:

Before opening any file, a file pointer needs to be established.

Syntax : Establishing a file pointer


FILE *fptr;

Where,
FILE is the structure which is defined in the header file <stdio.h>.

A file should be opened before any operation is being performed on it.


The fopen() function is being used for opening the file.

They can be accessed by using the following modes:

Closing a file
The fclose() function is used for closing a file.
When this function is used the file pointer is disconnected from a file.

Syntax:
int fclose(FILE *fp);
Where,
fp is the file pointer that points to the file that has to be closed.

An integer value is returned which will indicate if the function was successful or not.
In addition to the fclose() function we even have the fcloseall() function which will close all
the streams which are open currently except the standard streams (stdin, stdout and stderr).

Syntax:
intfcloseall(void);

This function will flush any of the stream buffers and will return the number of streams which
are closed.

Reading a file
Following are the list of functions which are used for reading a file:

Writing a file
Following are the list of functions which are used for writing a file:

Error handling in file operations


The function ferror() is used for checking the errors in the stream.

Syntax:
int ferror(FILE *stream);

This function returns 0 if there are no errors and a value if there are some errors.
Example 1: Write to a text file
#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;
// use appropriate location if you are using MacOS or Linux
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}

Example 2: Read from a text file


#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:\\program.txt","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}

You might also like