You are on page 1of 30

UNIT - IV

Function in C
We refer to a function as a group of various statements that perform a task together. Any C program
that we use has one function at least, that is main(). Then the programs can define multiple additional
functions in a code.

Use of the Function in C


One can easily divide a C program code into several separate functions. How we divide our available
code according to different available functions is totally up to us. But the division should occur
logically in such a way that every function is capable of performing a specific task.
The declaration of function informs the compiler about the name of the function, parameters, and return
type. In other words, the function definition helps in providing the actual body of any function that we
want in a program/ code.
We can also refer to functions as a sub-routine, a method, or a procedure in a program. The standard
library in C language provides its users with various built-in functions that the concerned programs can
call. For example, we can use the strcat() function for concentrating two strings, copy the location of
one memory to another location of memory using the memcpy() function, and many more.

Advantages of Using Functions in C Programming


The functions in the C programming language offer the following advantages to us:

• When we make use of the functions, then we can easily avoid the rewriting of the same code/
logic time and again multiple times in any program.
• The calling of C functions may appear as many numbers of times as we want in any program.
And we can do so from any place in the program that is given to us.
• We can perform the tracking of a large C program pretty easily if we divide it into various
functions.
• One of the primary achievements of the C functions is reusability.
• However, remember that the function calling always acts as an overhead in the case of a C
program.

Defining a Function in C
The function definition, in general, holds this form in the C programming language:
return_type name_of_function( parameter list ) {
function body
}
The function definition in the C programming language contains a function body and a function header.
Let us take a look at all the parts that a function consists of:

• Function Name − It denotes the actual name of any function that we are using in the given
code. The name and parameter of a function constitute a function signature in the code together.
• Function Body − It consists of a collection of all the statements. These provide a definition of
what the function will do in the code.
• Parameters − It is just like a placeholder. Whenever we invoke a function, we pass a value to
the available parameter. We refer to this value as an argument or an actual parameter. We refer
to the parameter list as the number, order, and type of the function in the code. The parameters
may be optional. It means that any function in a code may consist of no parameters at all.
• Return Type − We may get a value in return for a function. The term return type refers to the
data type of the returns that we get from the functions (function returns). Some of the functions
are also capable of performing any desired operation without getting a value in return for it. In
any such case, the keyword used for the return_type will be void.

Syntax of Function Aspects of Function

return_type name_of_function (argument list) {function body;} Function definition

name_of_function (argument_list) Function call

return_type name_of_function (argument list); Function declaration

Function Syntax
Here is the syntax that we use to create a function in the C programming language:
return_type name_of_function(data_type parameter…)
{
// executable code in c
}

Example
Here, we have given a source code below for the function max(). The max() function takes two of the
parameters- namely val1 and val2. It then returns the maximum value that is present between both of
them. Let us take a look:
/* the function returns the max in between two values */
int max(int val1, int val2) {
/* declaration of local variable */
int result;
if (val1 > val2)
result = val1;
else
result = val2;
return result;
}

Types of Functions
The C programming language has functions that are of the following types:

• User-defined Functions – These are the types of functions that we can create using the C
programmer so that we can make use of it multiple times. This function reduces the complexity
of any big program- and thus, optimizes the given code.
• Library Functions – These are the functions whose declaration occurs in the header files of C,
such as floor(), ceil(), outs(), gets(), printf(), scanf(), etc.

Return Value
Any function in the C programming may not return its value from any function. In case we don’t need
to return the value that is available in any function, we can make use of the void in the form of a return
type. Let us look at an example of the C function that does not perform the return of a value from the
available function.
Let us look at an example of a C function that has no return value:
void chocolate()
{
printf(“chocolate c”);
}
In case we want to return a value from an available function, we must make use of any of the data
types, such as char, long, int, etc. Thus, the return type depends totally on the value that needs to return
from the available function. We will look at an example of a C function that will return an int value
from the given function.
Example of a C function with int return value,
int get()
{
return 20;
}
In the example mentioned above, we are trying to return the value 20, and the data type, in this case, is
int. If we are willing to return to the value of the floating-point (example, 64.5, 7,9, 27.61, etc.), then
we must make use of the float in the form of the method’s return type.
float get()
{
return 83.7;
}
Here, we have to call a function so that we get the function’s value.

Function Calling – Different Aspects


The functions available in a code may accept an argument or may not accept it at all. Thus, it may
return any of the values or may not do so. On the basis of these facts, the function calls have the
following four aspects:

•A function that has no arguments and has no return value.


• A function that has no arguments but has a return value.
• A function that has arguments but has no return value.
• A function that has arguments and also has a return value.
Example of a function that has no arguments and has no return value,
#include<stdio.h>
void printName();
void main ()
{
printf(“Bye “);
printName();
}
void printName()
{
printf(“Kiddo”);
}
The output generated from this program would be:
Bye Kiddo
Example of a function that has no arguments but has a return value,
#include<stdio.h>
int sum();
void main()
{
printf(“By calculating the area of the square given\n”);
float area = square();
printf(“The area of the given square will be: %f\n”,area);
}
int square()
{
float side;
printf(“The length of the side of square in meters will be: “);
scanf(“%f”,&side);
return side * side;
}
The output generated from this program would be:
By calculating the area of the square given
The length of the side of the square in meters will be: 10
The area of the given square will be: 100.000000

Example of a function that has arguments but has no return value,


#include<stdio.h>
void sum(int, int);
void main()
{
int x,y,result;
printf(“\nCalculation of the sum of two values:”);
printf(“\nEntering of two values:”);
scanf(“%d %d”,&x,&y);
sum(x,y);
}
void sum(int x, int y)
{
printf(“\nThe sum of the two values is %d”,x+y);
}
The output generated from this program would be:
Calculation of the sum of two values:
Entering of two values 58
62
The sum of the two values is 120

Example of a function that has arguments and also has a return value,
#include<stdio.h>
int sum(int, int);
void main()
{
int x,y,result;
printf(“\nThe calculation of the sum of two values:”);
printf(“\nThe entering of two values:”);
scanf(“%d %d”,&x,&y);
result = sum(x,y);
printf(“\nThe sum is : %d”,result);
}
int sum(int x, int y)
{
return x+y;
}
The output generated from this program would be:
The calculation of the sum of two values:
The entering of two values: 49
51
The sum is: 100

Declaration of Function
The function definition basically tells a compiler about the name of the function and how one can call
this function. Then we can define the actual body of this function separately.
There are these following parts that exist in a function declaration:
return_type name_of_function(parameter list );
For the defined function above that is max(), the function declaration will occur in the following way:
int max(int val1, int val2);
The parameter names are not that important in the case of function declaration- we only require their
type. Thus, the declaration mentioned below is also going to be valid:
int max(int, int);
We only require the declaration of the function when we define that function in a source file while we
still call that function in a separate file. In any such case, we have to declare that function at the very
top of the file that calls that function.

Calling of a Function
When we create a function in C programming, we basically provide that function with a definition of
what it has to do. But to use this function, we need to call this function for performing its defined task.
When a function gets called by a program, the called function will get the program control transferred
to it. The called function will be performing a defined task. Once we execute the return statement or
when it reaches the closing brace of the function-ending, it is bound to return the program control to
the main program.
For calling a function, we simply have to pass the parameters required for it, along with the name of
the function. Here, if the function happens to return a value, then we can easily keep the returned value
stored with us.
For example −
#include <stdio.h>
/* declaration of function */
int max(int val1, int val2);
int main () {
/* definition of local variable */
int x = 400;
int y = 500;
int ret;
/* function calling for getting a max value */
ret = max(x, y);
printf( “The max value is : %d\n”, ret );
return 0;
}
/* function returns the max in between two values */
int max(int val1, int val2) {
/* declaration of local variable */
int result;
if (val1 > val2)
result = val1;
else
result = val2;
return result;
}
Output
In this case, we have kept the function max() with the function main(). After that, we have performed
the compilation of the source code. Running of the final executable would be producing the result that
follows:
The max value is: 500

Function Arguments
When a function needs to use the arguments, it has to declare those variables that happen to accept the
arguments’ values. Such variables are known as the given function’s formal parameters.
The formal parameters behave just like any other local variables inside our given function. These
parameters get created when they enter into a function. After that, it gets destroyed when it exits.
During the calling of a function, there will be two ways in which we can perform the passing of these
arguments to a given function:

Type of
Description of Call Type
Call

Call By The Call by Reference method creates a copy of the address of the given argument into
Reference the parameter that is formal in nature. Inside this function, the use of address helps in
accessing the actual argument that comes in use in this call. It means that the changes
that appear on the parameter are bound to affect the given argument.

Call By The Call by Value method creates a copy of the actual value of the given argument in
Value the parameter of the function that is formal in nature. Here, the changes that appear on
the parameter (that exists inside the function) create no effect whatsoever on the
available argument.
The C programming, by default, is the Call by Value for passing the arguments. Generally, it means
that we cannot make use of the code that exists within a function for altering the arguments that help
in calling the function.

Library Functions In C
The library functions in the C programming language are the inbuilt functions that are grouped together
and then placed in a common place known as the library. We make use of the library functions to
perform a specific type of operation. For example, the library function printf helps is printing on the
console. The designers of a compiler create the library functions. The defining of all the standard library
functions in C occurs inside multiple header files that are saved using the .h extension.
A user needs to include such header files in their program for utilizing the library functions that exist
in those header files. For instance, if we want to make use of scanf/ printf library functions, then we
have to include the stdio.h header file in our program. This header file consists of all library functions
that relate to standard output/ input.
Here is a list of some of the header files that is mostly utilized in the C programming:

Header Header file’s Description


file

conio.h It is a type of console output/ input header file.

stdio.h It is a standard type of output/ input header file. This header file consists of all the library
functions that are related to standard output/ input.

stdlib.h It is a type of header file that consists of various general library functions, such as exit(),
calloc(), malloc(), etc.

string.h This header file consists of all the library functions that are string-related, such as puts(),
gets(), etc.

time.h It is a type of header file that consists of all the functions that are time-related.

math.h It is a type of header file that consists of all the functions that are related to the math
operations, such as pow(), etc.

stdarg.h We use this header file for defining the variable argument functions.

ctype.h It is a type of header file that consists of the characters that handle the functions.

setjmp.h It is a type of header file that consists of all the functions that are jump functions.

signal.h We use this header file for defining any given signal handling function.

errno.h This type of header file consists of all the error handling functions.

locale.h It is a type of header file that consists of alL the locale functions.

assert.h It is a type of header file that consists of all the diagnostic functions.

What are the different aspects of function calls?


The functions available in a code may accept an argument or may not accept it at all. Thus, it may
return any of the values or may not do so. On the basis of these facts, the function calls have the
following four aspects:

• A function that has no arguments and has no return value.


• A function that has no arguments but has a return value.
• A function that has arguments but has no return value.
• A function that has arguments and also has a return value.

Why do we need to declare a function in a program?


The function definition basically tells a compiler about the name of the function and how one can call
this function. Then we can define the actual body of this function separately.
There are these following parts that exist in a function declaration:
return_type name_of_function(parameter list );

What is the importance of calling a function?


When we create a function in C programming, we basically provide that function with a definition of
what it has to do. But to use this function, we need to call this function for performing its defined task.
When a function gets called by a program, the called function will get the program control transferred
to it. The called function will be performing a defined task. Once we execute the return statement or
when it reaches the closing brace of the function-ending, it is bound to return back the program control
to the main program.
For calling a function, we simply have to pass the parameters required for it, along with the name of
the function. Here, if the function happens to return a value, then we can easily keep the returned value
stored with us.
Nesting of Functions
C language also allows nesting of functions i.e to use/call one function inside another
function's body. We must be careful while using nested functions, because it may lead
to infinite nesting.
function1()
{
// function1 body here
function2();
// function1 body here
}
If function2() also has a call for function1() inside it, then in that case, it will lead to an
infinite nesting. They will keep calling each other and the program will never terminate.
Not able to understand? Lets consider that inside the main() function, function1() is
called and its execution starts, then inside function1(), we have a call for function2(), so
the control of program will go to the function2(). But as function2() also has a call to
function1() in its body, it will call function1(), which will again call function2(), and this
will go on for infinite times, until you forcefully exit from program execution.
Recursion in C
Recursion is the process which comes into existence when a function calls a copy of itself to work on
a smaller problem. Any function which calls itself is called recursive function, and such function calls
are called recursive calls. Recursion involves several numbers of recursive calls. However, it is
important to impose a termination condition of recursion. Recursion code is shorter than iterative code
however it is difficult to understand.
Recursion cannot be applied to all the problem, but it is more useful for the tasks that can be defined
in terms of similar subtasks. For Example, recursion may be applied to sorting, searching, and traversal
problems.
Generally, iterative solutions are more efficient than recursion since function call is always overhead.
Any problem that can be solved recursively, can also be solved iteratively. However, some problems
are best suited to be solved by the recursion, for example, tower of Hanoi, Fibonacci series, factorial
finding, etc.

#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}
Output
Enter the number whose factorial you want to calculate?5
factorial = 120

Structure and Union


A Structure and Union in C can be passed by value to functions and returned by value by functions. In
structure, we can pass complete sets of records to any function using a single parameter. Union is
used when you have to use the same memory location for two or more data members.

What is Structure and Union in C?


The structure is the container defined in C to store data variables of different types and also supports
the user-defined variable’s storage. On the other hand, Union is also a similar kind of container in C
which can also hold the different types of variables along with the user-defined variables. A structure
contains an ordered group of data objects. Unlike the elements of an array, the data objects within a
structure can have varied data types. Each data object in a structure is a member or field. A union is
an object similar to a structure except that all of its members start at the same location in
memory.
▪ Structure: Structure is an arrangement and organization of interrelated elements in a material
object or system, or the object or system so organized. The structure is a user-defined data type
in C language which allows us to combine data of different types together. It helps to construct
complex data.
▪ Union: A union is a class all of whose data members are mapped to the same address within its
object. A union is a special data type available in C that allows to the storage of different data
types in the same memory location.
C Structure is a collection of different data types which are grouped together and each element in a C
structure is called a member. If you want to access structure members in C, structure variables should
be declared. In structure member and structure in C, every member is assigned a unique memory
location whereas in Union all the data members share a memory location.
In structure member change in the value of one data member does not affect other data members in the
structure whereas in structure in C change in the value of one data member affects the value of other
data members.in structure member, a structure can store multiple values of the different members
whereas in structure in C, a union stores one value at a time for all of its members. A structure’s total
size is the sum of the size of every data member and in structure in C

Difference between Structure and Union in C on the basis of keyword, memory, value altering,
accessing members, and initialization of members.

Structure Union

The keyword union is used to define a The keyword struct is defined as a structure
union.

Union is equal to the size of the largest Greater than or equal to the sum of sizes of
member. its members.

Memory allocated is shared by individual Each member within a structure is assigned


members of the union. a unique storage area of location.

Altering the value of any of the members Altering the value of a member will not
will alter other members’ values. affect other members of the structure.
Only one member can be accessed at a
time

Only the first member of the union can be Several members of a structure can be
initialized. initialized at once.

Syntax of declaring Structure


▪ struct Person { char name[50]; int citNo; float salary; }; Here, a derived type struct
Person is defined. Now, you can create variables of this type.
struct employee /* Defines a structure variable named temp */
{
char name[20];
int id;
long class;
} temp;

The employee structure has three members: name, id, and class. The name member is a 20-
element array, and id and class are simple members with int and long types, respectively. The
identifier employee is the structure identifier.

Syntax of Declaring Union


Union Employee
{
int age;
char name[50];
float salary; };

Here, a derived type union person is defined.

union sign /* A definition and a declaration */


{
int svar;
unsigned svar;
} number;
This example defines a union variable with sign type and declares a variable named number that
has two members: svar, a signed integer, and uvar, an unsigned integer. This declaration allows
the current value of a number to be stored as either a signed or an unsigned value. The tag
associated with this union type is a sign.

Advantages of Structure and Union in C


In Structure and Union in C,
▪ Structure Increased productivity,
▪ Structure in C eliminates lots of burdens while dealing with records which contain
heterogeneous data items, thereby increasing productivity. Maintainability of code: using
structure, we represent complex records by using a single name, which makes code
maintainability like a breeze.
In Structure and Union in C,
▪ Union It occupies less memory compared to structure.
▪ When you use union, only the last variable can be directly accessed. Union is used when you
have to use the same memory location for two or more data members. It enables you to hold
data of only one data member.
Disadvantages of Structure and Union in C
Following are the disadvantages of Structure and Union in C
▪ In a union you can use only one union member at a time.
▪ All the union variables cannot be initialized or used with varying values at a time.
▪ Union assigns one common storage space for all its members.
▪ Structure is slower because it requires storage space for all the data.
▪ If the complexity of an IT project goes beyond the limit, it becomes hard to manage.
▪ Change of one data structure in a code necessitates changes at many other places. Therefore,
the changes become hard to track.
Where and why do we use Structure and Union in C
You use a union when your “thing” can be one of many different things but only one at a time. You
use a structure when your “thing” should be a group of other things.
A structure is a user-defined data type available in C that allows combining data items of different
kinds. In structure and union in C the structures are used to represent a record. A union is a special data
type available in C that allows storing different data types in the same memory location.
Structure
▪ It is mainly used for storing various data types
▪ It occupies space for each and every member written in inner parameters
Union
▪ It is mainly used for storing one of the many data types that are available.
▪ It occupies space for a member having the highest size written in inner parameters.

Accessing structure members in c


1. Array elements are accessed using the Subscript variable , Similarly Structure members are
accessed using dot [.] operator.
2. (.) is called as “Structure member Operator”.
3. Use this Operator in between “Structure name” & “member name”

Declaring structure variable along with structure declaration


Syntax

struct name/tag
{
//structure members

} variables;

Example

struct car
{
char name[100];
float price;
} car1;

Declaring structure variable using struct keyword.


Syntax

struct name variables;


Example

struct car
{
char name[100];
float price;
};
struct car car1, car2, car3;

Initializing structure members


We can initialize the structrue members directly like below,
Example
struct car
{
char name[100];
float price;
};
//car1 name as "xyz"
//price as 987432.50

struct car car1 ={"xyz", 987432.50};

Example

#include<stdio.h>

int main()
{
struct car
{
char name[100];
float price;
};

// car1.name -> "Benz"


//car1.price -> 987432.50
struct car car1 ={"xyz", 987432.50};

//printing values using dot(.) or 'member access' operator


printf("Name of car = %s\n",car1.name);
printf("Price of car = %f\n",car1.price);

return 0;

Output
Name of car = Benz
Price of car = 987432.500000
Comparing two Structures
Comparing structures in c is not permitted to check or compare directly with logical operators.
Only structure members can be comparable with logical operator.

Like
struc_object_1.age == struc_object_2.age
Program

#include<stdio.h>
#include<conio.h>
struct student {
int rno;
char name[20];
int percentage;
};
void main()
{
clrscr();
//compare structure via members
struct student stu1 = {1001,"Ramesh",87};
struct student stu2 = {1002,"Arun",85};
if (stu1.percentage &lt; stu2.percentage){
printf("%s has higher marks.",stu2.name);
}
else {
printf("%s has higher marks.",stu1.name);
}
}

Output
Ramesh has higher marks.

Array of Structures in C
An array of structures in C can be defined as the collection of multiple structures
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.

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

Arrays within Structure


Sometimes, arrays may be the member within structure, this is known as arrays within
structure. Accessing arrays within structure is similar to accessing other members.
Purpose of Array within Structure
When you find yourself to store a string value, then you have to go for array within
structure. because your name comes under character data type alone, thus array is
capable of storing data of same data type.
C program - Arrays within Structure
#include <stdio.h>
int main()
{
struct student {
char name[30];
int rollno;
} stud;
printf ("Enter your RollNo : ");
scanf ("%d",&stud.rollno);
printf ("\nEnter your Name : ");
scanf ("%s", stud.name);
printf ("\nRollNo : %d\n Name : %s", stud.rollno, stud.name);
return 0;
}
Enter your RollNo : 16
Enter your Name : Abi
RollNo : 16
Name : Abi
Here stud act as an object for a structure student, so it's possible for us to access any
member inside a student using our object stud.
Structure within structure (or) Nested structures
A structure inside another structure is called nested structure.
Consider the following example,
struct emp{
int eno;
char ename[30];
float sal;
float da;
float hra;
float ea;
}e;
All the items comes under allowances can be grouped together and declared under a
sub – structure as shown below.
stuct emp{
int eno;
char ename[30];
float sal;
struct allowance{
float da;
float hra;
float ea;
}a;
}e;
The inner most member in a nested structure can be accessed by changing all the
concerned structure variables (from outer most to inner most) with the member using
dot operator.
UNIT - V

C Pointers

The pointer in C language is a variable which stores the address of another variable. This variable can
be of type int, char, array, function, or any other pointer. The size of the pointer depends on the
architecture. However, in 32-bit architecture the size of a pointer is 2 byte.

Consider the following example to define a pointer which stores the address of an integer.

1. int n = 10;
2. int* p = &n; // Variable p of type pointer is pointing to the address of the variable n of type in
teger.

Declaring a pointer

The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection
pointer used to dereference a pointer.

1. int *a;//pointer to int


2. char *c;//pointer to char

Pointer Example

An example of using pointers to print the address and value is given below.

As you can see in the above figure, pointer variable stores the address of number variable, i.e., fff4.
The value of number variable is 50. But the address of pointer variable p is aaa3.

By the help of * (indirection operator), we can print the value of pointer variable p.

Let's see the pointer example as explained for the above figure.

#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number;//stores the address of number variable
printf("Address of p variable is %x \n",p); // p contains the address of the number therefore printi
ng p gives the address of number.
printf("Value of p variable is %d \n",*p); // As we know that * is used to dereference a pointer the
refore if we print *p, we will get the value stored at the address contained by p.
return 0;
}

Output

Address of number variable is fff4


Address of p variable is fff4
Value of p variable is 50

Pointer to array

1. int arr[10];
2. int *p[10]=&arr; // Variable p of type pointer is pointing to the address of an integer array arr.

Pointer to a function

1. void show (int);


2. void(*p)(int) = &display; // Pointer p is pointing to the address of a function

Pointer to structure

1. struct st {
2. int i;
3. float f;
4. }ref;
5. struct st *p = &ref;

Advantage of pointer

1) Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc.
and used with arrays, structures, and functions.

2) We can return multiple values from a function using the pointer.

3) It makes you able to access any memory location in the computer's memory.
Usage of pointer

There are many applications of pointers in c language.

1) Dynamic memory allocation

In c language, we can dynamically allocate memory using malloc() and calloc() functions where the
pointer is used.

2) Arrays, Functions, and Structures

Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and
improves the performance.

Pointer to Array

Use a pointer to an array, and then use that pointer to access the array elements. For example,

#include<stdio.h>
void main()
{
int a[3] = {1, 2, 3};
int *p = a;
for (int i = 0; i < 3; i++)
{
printf("%d", *p);
p++;
}
return 0;
}

Output
123
Syntax:

*(a+i) //pointer with an array is same as: a[i]

Array of Pointers in C
When we want to point at multiple variables or memories of the same data type in a C program, we use
an array of pointers.

Let us assume that a total of five employees are working at a cheesecake factory. We can store the
employees’ names in the form of an array. Along with this, we also store the names of employees
working at the office, the library, and the shoe store.

Now, let us assume that once we read all the names of the employees randomly, we want to sort all of
the employees’ names working in the cheesecake factory. Sorting all the employee names requires
reading, swapping, and copying a lot of data. But since we have stored all the employee names in
groups/ arrays, we can directly refer to the array of names of employees working at the cheesecake
factory.

The Application of Arrays of Pointers

Let us assume that we want to build an enclosed system, and this system uses a different kind of
thermometer for measuring the temperature. Now, in this case, we can use an array for holding the
address of memory for every sensor. This way, manipulation of the sensor status becomes very easy.

Example

The thermo[0] will be holding the 1st sensor’s address.

The thermo[1] will be holding the 2nd sensor’s address and so on.

Now, since it’s an array, it can interact directly with the thermo pointer indexed in the array. Thus, we
will get the 1st sensor’s status with the thermo[0], the second one using the thermo[1], and so on ahead.

Declaration of an Array of Pointers in C

An array of pointers can be declared just like we declare the arrays of char, float, int, etc. The syntax
for declaring an array of pointers would be:

data_type *name_of_array [array_size];

Now, let us take a look at an example for the same,

int *ary[55]

This one is an array of a total of 55 pointers. In simple words, this array is capable of holding the
addresses a total of 55 integer variables. Think of it like this- the ary[0] will hold the address of one
integer variable, then the ary[1] will hold the address of the other integer variable, and so on.

Pointers as Function Argument in C


Pointer as a function parameter is used to hold addresses of arguments passed during function call.
This is also known as call by reference. When a function is called by reference any change made to
the reference variable will effect the original variable.

Example: Swapping two numbers using Pointer

#include <stdio.h>
void swap(int *a, int *b);
int main()
{
int m = 10, n = 20;
printf("m = %d\n", m);
printf("n = %d\n\n", n);
swap(&m, &n); //passing address of m and n to the swap function
printf("After Swapping:\n\n");
printf("m = %d\n", m);
printf("n = %d", n);
return 0;
}
/*
pointer 'a' and 'b' holds and
points to the address of 'm' and 'n'
*/
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Output:
m = 10
n = 20
After Swapping:
m = 20
n = 10

Functions returning Pointer variables

A function can also return a pointer to the calling function. In this case you must be careful, because
local variables of function don’t live outside the function. They have scope only inside the function.
Hence if you return a pointer connected to a local variable, that pointer will be pointing to nothing
when the function ends.
File Management
What is File Handling in C?
File handling refers to the method of storing data in the C program in the form of an output or input that might have
been generated while running a C program in a data file, i.e., a binary file or a text file for future analysis and
reference in that very program.

What is a File in C?
A file refers to a source in which a program stores the information/data in the form of bytes of sequence on a disk
(permanently). The content available on a file isn’t volatile like the compiler memory in C. But the program can
perform various operations, such as creating, opening, reading a file, or even manipulating the data present inside
the file. This process is known as file handling in C.

Why Do We Need File Handling in C?


There are times when the output generated out of a program after its compilation and running do not serve our
intended purpose. In such cases, we might want to check the program’s output various times. Now, compiling and
running the very same program multiple times becomes a tedious task for any programmer. It is exactly where file
handling becomes useful.
Let us look at a few reasons why file handling makes programming easier for all:

• Reusability: File handling allows us to preserve the information/data generated after we run the program.
• Saves Time: Some programs might require a large amount of input from their users. In such cases, file
handling allows you to easily access a part of a code using individual commands.
• Commendable storage capacity: When storing data in files, you can leave behind the worry of storing all
the info in bulk in any program.
• Portability: The contents available in any file can be transferred to another one without any data loss in the
computer system. This saves a lot of effort and minimises the risk of flawed coding.

Types of Files in a C Program


When referring to file handling, we refer to files in the form of data files. Now, these data files are available in 2
distinct forms in the C language, namely:

• Text Files
• Binary Files

Text Files
The text files are the most basic/simplest types of files that a user can create in a C program. We create the text files
using an extension .txt with the help of a simple text editor. In general, we can use notepads for the creation of .txt
files. These files store info internally in ASCII character format, but when we open these files, the content/text
opens in a human-readable form.
Text files are, thus, very easy to access as well as use. But there’s one major disadvantage; it lacks security. Since a
.txt file can be accessed easily, information isn’t very secure in it. Added to this, text files consume a very large
space in storage.
To solve these problems, we have a different type of file in C programs, known as binary files.

Binary Files
The binary files store info and data in the binary format of 0’s and 1’s (the binary number system). Thus, the files
occupy comparatively lesser space in the storage. In simpler words, the binary files store data and info the same
way a computer holds the info in its memory. Thus, it can be accessed very easily as compared to a text file.
The binary files are created with the extension .bin in a program, and it overcomes the drawback of the text files in
a program since humans can’t read it; only machines can. Thus, the information becomes much more secure. Thus,
binary files are safest in terms of storing data files in a C program.

Operators/Functions that We Use for File Handling in C


We can use a variety of functions in order to open a file, read it, write more data, create a new file, close or delete a
file, search for a file, etc. These are known as file handling operators in C.
Here’s a list of functions that allow you to do so:

Description of Function Function in Use

used to open an existing file or a new file fopen()

writing data into an available file fprintf()

reading the data available in a file fscanf()

writing any character into the program file fputc()

reading the character from an available file fgetc()

used to close the program file fclose()

used to set the file pointer to the intended file position fseek()

writing an integer into an available file fputw()

used to read an integer from the given file fgetw()

used for reading the current position of a file ftell()

sets an intended file pointer to the file’s beginning itself rewind()

Note: It is important to know that we must declare a file-type pointer when we are working with various files in a
program. This helps establish direct communication between a program and the files.
Here is how you can do it:
FILE *fpointer;
Out of all the operations/functions mentioned above, let us discuss some of the basic operations that we perform in
the C language.

Operations Done in File Handling


The process of file handling enables a user to update, create, open, read, write, and ultimately delete the file/content
in the file that exists on the C program’s local file system. Here are the primary operations that you can perform on
a file in a C program:

• Opening a file that already exists


• Creating a new file
• Reading content/ data from the existing file
• Writing more data into the file
• Deleting the data in the file or the file altogether

Opening a File in the Program – to create and edit data


We open a file with the help of the fopen() function that is defined in the header file- stdio.h.
Here is the syntax that we follow when opening a file:
ptr = fopen (“openfile” , “openingmode”);
Let us take a look at an example for the same,
fopen (“E:\\myprogram\\recentprogram.txt” , “w”);
fopen (“E:\\myprogram\\previousprogram.bin” , “rb”);

• Here, if we suppose that the file – recentprogram.txt doesn’t really exist in the E:\\myprogram location.
Here, we have used the mode “w”. Thus, the first function will create a new file with the name
recentprogram.txt and then open it for writing (since we have used the “w” mode).
• The “w” here refers to writing mode. It allows a programmer to overwrite/edit and create the contents in a
program file.
• Now, let us take a look at the second binary previousprogram.bin file that is present in the E:\\myprogram
location. Thus, the second function here will open the file (that already exists) for reading in the “rb”
binary mode.
• The “rb” refers to the reading mode. It only allows you to read a file, but not overwrite it. Thus, it will only
read this available file in the program.
Let us take a look at a few more opening modes used in the C programs:

Opening Modes of C in Standard I/O of a Program

Mode in Meaning of Mode When the file doesn’t exist


Program

r Open a file for reading the content. In case the file doesn’t exist in the
location, then fopen() will return NULL.
rb Open a file for reading the content in binary In case the file doesn’t exist in the
mode. location, then fopen() will return NULL.

w Open a file for writing the content. In case the file exists, its contents are
overwritten.
In case the file doesn’t exist in the
location, then it will create a new file.

wb Open a file for writing the content in binary In case the file exists, then its contents
mode. will get overwritten.
In case the file doesn’t exist in the
location, then it will create a new file.

a Open a file for appending the content. In case the file doesn’t exist in the
location, then it will create a new file.
Meaning, the data of the program is added to
the file’s end in a program.

ab Open a file for appending the content in binary In case the file doesn’t exist in the
mode. location, then it will create a new file.
Meaning, the data of the program is added to
the file’s end in a program in a binary mode.

r+ Open a file for both writing and reading the In case the file doesn’t exist in the
content. location, then fopen() will return NULL.

rb+ Open a file for both writing and reading the In case the file doesn’t exist in the
content in binary mode. location, then fopen() will return NULL.

w+ Open a file for both writing and reading. In case the file exists, its contents are
overwritten.
In case the file doesn’t exist in the
location, then it will create a new file.

wb+ Open a file for both writing and reading the In case the file exists, its contents are
content in binary mode. overwritten.
In case the file doesn’t exist in the
location, then it will create a new file.

a+ Open a file for both appending and reading the In case the file doesn’t exist in the
content. location, then it will create a new file.

ab+ Open a file for both appending and reading the In case the file doesn’t exist in the
content in binary mode. location, then it will create a new file.

How do we close a file?


Once we write/read a file in a program, we need to close it (for both binary and text files). To close a file, we utilise
the fclose() function in a program.
Here is how the program would look like:
fclose(fptr);
In this case, the fptr refers to the file pointer that is associated with that file that needs to be closed in a program.

How do we read and write the data to the text file?


We utilise the fscanf() and fprintf() to write and read the data to the text file. These are basically the file versions of
the scanf() and printf(). But there is a major difference, i.e., both fscanf() and fprintf() expect a pointer pointing
towards the structure FILE in the program.

Writing Data to the Text File in a Program


#include <stdio.h>
#include <stdlib.h>
int main()
{
int val;
FILE *fptr;
// if you are using Linux or MacOS, then you must use appropriate locations
fptr = fopen (“C:\\currentprogram.txt”,”w”);
if(fptr == NULL)
{
printf(“File type invalid!”);
exit(1);
}
printf(“Please enter the val: “);
scanf(“%d”,&val);
fprintf(fptr,”%d”,val);
fclose(fptr);
return 0;
}
The program mentioned here would take the number given by then store it in the currentprogram.txt file.
Once we compile this program and run it on the system, we will be able to witness a currentprogram.txt text file
created in the C drive of our computer! Also, when we open this file, then we will be able to see what integer we
entered as an input while coding.

Reading Information from the Text File in a Program


#include <stdio.h>
#include <stdlib.h>
int main()
{
int val;
FILE *fptr;
// The program will exit in case the file pointer fptr returns NULL.
if ((fptr = fopen(“C:\\currentprogram.txt”,”r”)) == NULL){
printf(“Visible error detected. Cannot open the file!”);
exit(1);
}
fscanf(fptr,”%d”, &val);
printf(“The value of the integer n is=%d”, val);
fclose(fptr);
return 0;
}
The program given here would read the integer that we have input in the currentprogram.txt file and then print the
integer as an output on the computer screen.
In case you were successful in creating the file with the help of Example 1, then the running of the program in
Example 2 will generate the integer that you have input.
You can also use other functions such as fputc(), fgetchar(), etc., in a similar manner in the program.

Questions

What is file handling in C?


File handling refers to the method of storing data in the C program in the form of an output or input that might have
been generated while running a C program in a data file, i.e., a binary file or a text file for future analysis and
reference in that very program.

What is file handling for?


There are times when the output generated out of a program after its compilation and running do not serve our
intended purpose. In such cases, we might want to check the program’s output various times. Now, compiling and
running the very same program multiple times becomes a tedious task for any programmer. It is exactly where file
handling becomes useful.

What are file handling operations?


We can use a variety of functions in order to open a file, read it, write more data, create a new file, close or delete a
file, search for a file, etc. These are known as file handling operators in C.

What is the difference between text and binary files?


We create the text files using an extension .txt with the help of a simple text editor. The binary files store info and
data in the binary format of 0’s and 1’s (the binary number system). The binary files are created with the extension
.bin in a program, and it overcomes the drawback of the text files in a program.

You might also like