0% found this document useful (0 votes)
18 views48 pages

DS 2nd UNIT

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views48 pages

DS 2nd UNIT

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

C Functions

In c, we can divide a large program into the basic building blocks known as function. The
function contains the set of programming statements enclosed by {}. A function can be called
multiple times to provide reusability and modularity to the C program. In other words, we can
say that the collection of functions creates a program. The function is also known
as procedureor subroutinein other programming languages.

Advantage of functions in C

There are the following advantages of C functions.

o By using functions, we can avoid rewriting same logic/code again and again in a
program.
o We can call C functions any number of times in a program and from any place in a
program.
o We can track a large C program easily when it is divided into multiple functions.
o Reusability is the main achievement of C functions.
o However, Function calling is always a overhead in a C program.

Function Aspects

There are three aspects of a C function.

o Function declaration A function must be declared globally in a c program to tell the


compiler about the function name, function parameters, and return type.

o Function call Function can be called from anywhere in the program. The parameter list
must not differ in function calling and function declaration. We must pass the same
number of functions as it is declared in the function declaration.

Function definition It contains the actual statements which are to be executed. It is


the most important aspect to which the control comes when the function is called. Here, we
must notice that only one value can be returned from the function.
The syntax of creating function in c language is given below:

o return_type function_name(data_type parameter...)


o {
o //code to be executed
o }
o
C function aspects Syntax

Function declaration return_typefunction_name (argument list);

Function call function_name (argument_list)

return_typefunction_name (argument list)


Function definition
{function body;}

Types of Functions

There are two types of functions in C programming:

1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), ceil(), floor() etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.

C Library Functions


The Standard Function Library in C is a huge library of sub-libraries, each of which contains the
code for several functions. In order to make use of these libraries, link each library in the broader
library through the use of header files. The actual definitions of these functions are stored in
separate library files, and declarations in header files. In order to use these functions, we have to
include the header file in the program. Below are some header files with descriptions:

Example:

The math.h header defines various mathematical functions and one macro. All the
<math.h> Functions
in this library take double as an argument and return double as the result.

The stdio.h header defines three variable types, several macros, and various
<stdio.h>
function for performing input and output.

<time.h> Defines date and time handling functions.

Strings are defined as an array of characters. The difference between a character


<string.h> array
and a string is that a string is terminated with a special character ‘\0’.

User-Defined Function in C



A user-defined function is a type of function in C language that is defined by the user to


perform some specific task. It provides code reusability and modularity to our program. User-
defined functions are different from built-in functions as their working is specified by the user
and no header file is required for their usage.

Return Value:
A C function may or may not return a value from the function. If you don't have to return any
value from the function, use void for the return type.

Let's see a simple example of C function that doesn't return any value from the function.

Example without return value:

1. void hello(){
2. printf("hello c");
3. }

Example for Function with argument and with return value


Example 1

1. #include<stdio.h>
2. int sum(int, int);
3. void main()
4. {
5. int a,b,result;
6. printf("\nGoing to calculate the sum of two numbers:");
7. printf("\nEnter two numbers:");
8. scanf("%d %d",&a,&b);
9. result = sum(a,b);
10. printf("\nThe sum is : %d",result);
11. }
12. int sum(int a, int b)
13. {
14. return a+b;
15. }

Output:

Going to calculate the sum of two numbers:


Enter two numbers:10
20
The sum is : 30

Parameter Passing Techniques in C


Last Updated : 11 Oct, 2024


In C, there are different ways in which parameter data can be passed into and out of methods and functions. Let us assume that a function B() is called from another
function A(). In this case, A is called the “caller function” and B is called the “called function or callee function”. Also, the arguments which A sends to B are
called actual arguments and the parameters of B are called formal arguments.
Terminology
 Formal Parameter: A variable and its type as it appears in the prototype of the function or method.
 Actual Parameter: The variable or expression corresponding to a formal parameter that appears in the function or method call in the calling environment.

Parameter passing techniques in C, such as pass by value and pass by reference, are fundamental for controlling data flow. If you’re looking to master these concepts
alongside their use in data structures, the C Programming Course Online with Data Structures provides in-depth lessons on function handling and parameter
management.

Methods of Parameter Passing in C


There are two ways in which we can pass the parameters to the function in C:

1. Pass By Value
This method uses in-mode semantics. Changes made to formal parameters do not get transmitted back to the caller. Any modifications to the formal parameter
variable inside the called function or method affect only the separate storage location and will not be reflected in the actual parameter in the calling environment. This
method is also called call by value.

Example of Pass by Value


The below example demonstrates pass by value in function.
C

// C program to illustrate
// call by value
#include <stdio.h>

void func(int a, int b)


{
a += b;
printf("In func, a = %d b = %d\n", a, b);
}
int main(void)
{
int x = 5, y = 7;

// Passing parameters
func(x, y);
printf("In main, x = %d y = %d\n", x, y);
return 0;
}

Output

In func, a = 12 b = 7
In main, x = 5 y = 7

2. Pass By Reference in C
In this method, the address of an argument is passed to the function instead of the argument itself during the function call. Due to this, any changes made in the
function will be reflected in the original arguments. We use the address operator (&) and indirection operator (*) to provide an argument to a function via
reference.
When any argument is passed by reference in the function call as a parameter, it is passed using the address of(&) operator from the main function. In the
function definition, the function takes the value of the parameter by using (*) operator. By using this, it can directly access the value of the parameter directly from
its original location. There will be no need for extra memory or copying the same data into some other fields.
Also, a pointer type must be defined for the matching parameter in the called function in C.
Syntax

The code will look like this in the pass-by-reference method:


// function definion
return_type functionName (arg_type *arg1, arg_type *arg1, ......) {
// function body

}
..
// function call
functionName (&arg1, &arg2, ....);
Example of Pass by Reference
In the below program, the arguments that are passed by reference will be swapped with each other.

// C program to swap two numbers

#include <stdio.h>

// function definition with relevant pointers to recieve the

// parameters

void swap(int* a, int* b)

// accessing arguments like pointers

int temp = *a;

*a = *b;

*b = temp;

// driver code

int main(void)

{ int n1 = 5;

int n2 = 10;

// value before swapping

printf(" Before swapping : n1 is %d and n2 is %d\n", n1, n2);

// calling the function by passing the address of the

// arguments

swap(&n1, &n2);

// value after swapping

printf(" After swapping : n1 is %d and n2 is %d\n", n1, n2);


return 0;

Output

Before swapping : n1 is 5 and n2 is 10


After swapping : n1 is 10 and n2 is 5

3. Pass by Pointers
This technique uses a pointer. In function we pass memory address (pointer) of a variable rather than passing the actual value of variable. This passing technique
allows the function to access and modify the content at that particular memory location.
Example of Pass by Pointers
C

// C program to demonstrate the pass by pointer in Function

#include <stdio.h>

// Function to modify the value passed as pointer to an int


void modifyVal(int* myptr)
{
// Access and modifying the value pointed by myptr
*myptr = *myptr + 5;
}

int main()
{

int x = 5;
int* myptr = &x;

// Passing the pointer ptr to the function


modifyVal(myptr);

// printitng the modified value of x


printf("Modified value of x is: %d\n", x);
return 0;
}

Output

Modified value of x is: 10


Shortcomings of Pass by Pointers
 Pointers can be null so null pointer Issues arises if properly not checked.
 If more than one pointers point to the same memory location then changes made by one pointer affect other the other pointers which points to same memory
location.
 memory management should be done effectively using function like malloc and fre

C Function Prototype
A function prototype is also known as a function declaration which specifies the function’s name, function
parameters, and return type. The function prototype does not contain the body of the function. It is basically used to inform
the compiler about the existence of the user-defined function which can be used in the later part of the program.

Syntax

return_typefunction_name(type1 arg1, type2 arg2, ... typeNargN);


We can also skip the name of the arguments in the function prototype. So,
return_typefunction_name(type1 , type2 , ... typeN);
C Function Definition
Once the function has been called, the function definition contains the actual statements that
will be executed. All the statements of the function definition are enclosed within { } braces.

Syntax

return_typefunction_name (type1 arg1, type2 arg2 .... typeNargN) {

// actual statements to be executed


// return value if any

C Function Call
In order to transfer control to a user-defined function, we need to call it. Functions are called
using their names followed by round brackets. Their arguments are passed inside the brackets.
Syntax
function_name(arg1, arg2, ... argN);

Advantages of User-Defined Functions

The advantages of using functions in the program are as follows:


 One can avoid duplication of code in the programs by using functions. Code can be written
more quickly and be more readable as a result.
 Code can be divided and conquered using functions. This process is known as Divide and
Conquer. It is difficult to write large amounts of code within the main function, as well as
testing and debugging. Our one task can be divided into several smaller sub-tasks by using
functions, thus reducing the overall complexity.
 For example, when using pow, sqrt, etc. in C without knowing how it is implemented, one
can hide implementation details with functions.
 With little to no modifications, functions developed in one program can be used in another,
reducing the development time.

Structures in C

A structure in C is a derived or user-defined data type. We use the keyword struct to define a
custom data type that groups together the elements of different types. The difference between an
array and a structure is that an array is a homogenous collection of similar types, whereas a
structure can have elements of different types stored adjacently and identified by a name.
We are often required to work with values of different data types having certain relationships
among them. For example, a book is described by
its title (string), author (string), price (double), number of pages (integer), etc. Instead of using
four different variables, these values can be stored in a single struct variable.
Declare (Create) a Structure

You can create (declare) a structure by using the "struct" keyword followed by the structure_tag
(structure name) and declare all of the members of the structure inside the curly braces along
with their data types.
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member.

Syntax of Structure Declaration

The format (syntax) to declare a structure is as follows −

struct[structure tag]{
member definition;
member definition;
...
member definition;
}[one or more structure variables];

At the end of the structure's definition, before the final semicolon, you can specify one or more
structure variables but it is optional.
Example

In the following example we are declaring a structure for Book to store the details of a Book −

structbook{
char title[50];
char author[50];
double price;
int pages;
} book1;
Here, we declared the structure variable book1 at the end of the structure
definition. However, you can do it separately in a different statement.

Structure Variable Declaration

To access and manipulate the members of the structure, you need to declare its variable first. To
declare a structure variable, write the structure name along with the "struct" keyword followed
by the name of the structure variable. This structure variable will be used to access and
manipulate the structure members.

Example

The following statement demonstrates how to declare (create) a structure variable

structbook book1;
Usually, a structure is declared before the first function is defined in the program, after
the include statements. That way, the derived type can be used for declaring its variable inside
any function.

Structure Initialization

The initialization of a struct variable is done by placing the value of each element inside curly
brackets.

Example

The following statement demonstrates the initialization of structure


structbook book1 ={"Learn C","Dennis Ritchie",675.50,325};

Accessing the Structure Members

To access the members of a structure, first, you need to declare a structure variable and then use
the dot (.) operator along with the structure variable.

Example 1
The four elements of the struct variable book1 are accessed with the dot (.) operator. Hence,
"book1.title" refers to the title element, "book1.author" is the author name, "book1.price" is the
price, "book1.pages" is the fourth element (number of pages).

Take a look at the following example −

Open Compiler

#include<stdio.h>

structbook{
chartitle[10];
charauthor[20];
double price;
int pages;
};

intmain(){
structbook book1 ={"Learn C","Dennis Ritchie",675.50,325};

printf("Title: %s \n", book1.title);


printf("Author: %s \n", book1.author);
printf("Price: %lf\n", book1.price);
printf("Pages: %d \n", book1.pages);
printf("Size of book struct: %d",sizeof(structbook));
return0;
}

Output
Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Size of book struct: 48

Example 2
In the above program, we will make a small modification. Here, we will put the type
definition and the variable declaration together, like this −
structbook{
chartitle[10];
charauthor[20];
double price;
int pages;
} book1;

Note that if you a declare a struct variable in this way, then you cannot initialize it with curly
brackets. Instead, the elements need to be assigned individually.

Open Compiler

#include<stdio.h>
#include<string.h>

structbook{
chartitle[10];
charauthor[20];
double price;
int pages;
} book1;

intmain(){
strcpy(book1.title,"Learn C");
strcpy(book1.author,"Dennis Ritchie");
book1.price =675.50;
book1.pages =325;

printf("Title: %s \n", book1.title);


printf("Author: %s \n", book1.author);
printf("Price: %lf \n", book1.price);
printf("Pages: %d \n", book1.pages);
return0;
}
Output

When you execute this code, it will produce the following output −

Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325

Copying Structures

The assignment (=) operator can be used to copy a structure directly. You can also use the
assignment operator (=) to assign the value of the member of one structure to another.
Let's have two struct book variables, book1 and book2. The variable book1 is initialized with
declaration, and we wish to assign the same values of its elements to that of book2.

We can assign individual elements as follows −

structbook book1 ={"Learn C","Dennis Ritchie",675.50,325}, book2;


strcpy(book2.title, book1.title);
strcpy(book2.author, book1.author);
book2.price = book1.price;
book2.pages = book1.pages;
Note the use of strcpy() function to assign the value to a string variable instead of using the "=
operator".

Example

You can also assign book1 to book2 so that all the elements of book1 are respectively assigned
to the elements of book2. Take a look at the following program code −

Open Compiler

#include<stdio.h>
#include<string.h>
structbook{
chartitle[10];
charauthor[20];
double price;
int pages;
};

intmain(){
structbook book1 ={"Learn C","Dennis Ritchie",675.50,325}, book2;
book2 = book1;

printf("Title: %s \n", book2.title);


printf("Author: %s \n", book2.author);
printf("Price: %lf \n", book1.price);
printf("Pages: %d \n", book1.pages);
printf("Size of book struct: %d",sizeof(structbook));
return0;
}
Output

Run the code and check its output −

Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Size of book struct: 48

Structures as Function Arguments

You can pass a structure as a function argument in the same way as you pass any other variable
or pointer.

Example

Take a look at the following program code. It demonstrates how you can pass a structure as a
function argument −
Open Compiler

#include<stdio.h>
#include<string.h>

structBooks{
chartitle[50];
charauthor[50];
charsubject[100];
intbook_id;
};

/* function declaration */
voidprintBook(structBooks book);

intmain(){
structBooks Book1;/* Declare Book1 of type Book */
structBooks Book2;/* Declare Book2 of type Book */

/* book 1 specification */
strcpy(Book1.title,"C Programming");
strcpy(Book1.author,"Nuha Ali");
strcpy(Book1.subject,"C Programming Tutorial");
Book1.book_id =6495407;

/* book 2 specification */
strcpy(Book2.title,"Telecom Billing");
strcpy(Book2.author,"Zara Ali");
strcpy(Book2.subject,"Telecom Billing Tutorial");
Book2.book_id =6495700;

/* print Book1 info */


printBook(Book1);

/* Print Book2 info */


printBook(Book2);
return0;
}

voidprintBook(structBooks book){

printf("Book title : %s\n",book.title);


printf("Book author : %s\n",book.author);
printf("Book subject : %s\n",book.subject);
printf("Book book_id : %d\n",book.book_id);
}
Output

When the above code is compiled and executed, it produces the following result −

Book title : C Programming


Book author :Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700

Pointers to Structures

You can define pointers to structures in the same way as you define pointers to any other
variable.

Declaration of Pointer to a Structure

You can declare a pointer to a structure (or structure pointer) as follows −

structBooks*struct_pointer;

Initialization of Pointer to a Structure


You can store the address of a structure variable in the above pointer variable struct_pointer. To
find the address of a structure variable, place the '&' operator before the structure's name as
follows −
struct_pointer=& book1;
Let's store the address of a struct variable in a struct pointer variable.

structbook{
chartitle[10];
charauthor[20];
double price;
int pages;
};
structbook book1 ={"Learn C","Dennis Ritchie",675.50,325},
structbook*strptr;

Accessing Members Using Pointer to a Structure


To access the members of a structure using a pointer to that structure, you must use the →
operator as follows −
struct_pointer->title;
C defines the → symbol to be used with struct pointer as the indirection operator (also
called struct dereference operator). It helps to access the elements of the struct variable to
which the pointer reference to.

Example
In this example, strptr is a pointer to struct book book1 variable. Hence, strrptr→title returns
the title, just like book1.title does.
Open Compiler

#include<stdio.h>
#include<string.h>

structbook{
chartitle[10];
charauthor[20];
double price;
int pages;
};

intmain(){
structbook book1 ={"Learn C","Dennis Ritchie",675.50,325};
structbook*strptr;
strptr=&book1;
printf("Title: %s \n",strptr-> title);
printf("Author: %s \n",strptr-> author);
printf("Price: %lf \n",strptr-> price);
printf("Pages: %d \n",strptr-> pages);
return0;
}
Output

When you run this code, it will produce the following output −

Title: Learn C
Author: Dennis Ritchie
Price: 675.500000
Pages: 325
Note: The dot (.) operator is used to access the struct elements via the struct variable. To access
the elements via its pointer, we must use the indirection (->) operator
.

A struct variable is like a normal variable of primary type, in the sense that you can have an array
of struct, you can pass the struct variable to a function, as well as return a struct from a function.

You may have noted that you need to prefix "struct type" to the name of the variable or pointer at
the time of declaration. This can be avoided by creating a shorthand notation with the help
of typedef keyword.

Keyword typedef

We use the typedef keyword to create an alias name for data types. It is commonly used with
structures to simplify the syntax of declaring variables.
For example, let us look at the following code:

structDistance{
int feet;
float inch;
};

intmain() {
structDistanced1, d2;
}

We can use typedef to write an equivalent code with a simplified syntax:

typedefstructDistance {
int feet;
float inch;
} distance d1,d2;

intmain() {
distances d1, d2;
}

C Unions



The Union is a user-defined data type in C language that can contain elements of the different data types
just like structure. But unlike structures, all the members in the C union are stored in the same memory
location. Due to this, only one member can store data at the given instance.

Syntax of Union in C

The syntax of the union in C can be divided into three steps which are as follows:
C Union Declaration
In this part, we only declare the template of the union, i.e., we only declare the members’
names and data types along with the name of the union. No memory is allocated to the union in
the declaration.
unionunion_name {
datatype member1;
datatype member2;
...
};

Different Ways to Define a Union Variable


We need to define a variable of the union type to start using union members. There are two
methods using which we can define a union variable.
1. With Union Declaration
2. After Union Declaration
1. Defining Union Variable with Declaration
unionunion_name {
datatype member1;
datatype member2;
...
} var1, var2, ...;
2. Defining Union Variable after Declaration
unionunion_name var1, var2, var3...;
where union_name is the name of an already declared union.

Access Union Members


We can access the members of a union by using the ( . ) dot operator just like structures.
var1.member1;
where var1 is the union variable and member1 is the member of the union.
The above method of accessing the members of the union also works for the nested unions.
var1.member1.memberA;
Here,
 var1 is a union variable.
 member1 is a member of the union.
 memberA is a member of member1.

Initialization of Union in C
The initialization of a union is the initialization of its members by simply assigning the value
to it.
var1.member1 = some_value;
One important thing to note here is that only one member can contain some value at a given
instance of time.

Example of Union in C
// C Program to demonstrate how to use union
#include<stdio.h>

// union template or declaration


unionun{
intmember1;
charmember2;
floatmember3;
};

// driver code
intmain()
{

// defining a union variable


unionunvar1;

// initializing the union member


var1.member1=15;

printf("The value stored in member1 = %d",


var1.member1);

return0;
}

Output

The value stored in member1 = 15

Size of Union
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.

Difference between C Structure and C Union


The following table lists the key difference between the structure and union in C:
Structure Union

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

The structure can contain data in multiple members at Only one member can contain data
the same time. at the same time.
C Pointers



Pointers are one of the core components of the C programming language. A pointer can be used
to store the memory address of other variables, functions, or even other pointers. The use of
pointers allows low-level memory access, dynamic memory allocation, and many other
functionality in C.
In this article, we will discuss C pointers in detail, their types, uses, advantages, and
disadvantages with examples.

What is a Pointer in C?
A pointer is defined as a derived data type that can store the address of other C variables or a
memory location. We can access and manipulate the data stored in that memory location using
pointers.
As the pointers in C store the memory addresses, their size is independent of the type of data
they are pointing to. This size of pointers in C only depends on the system architecture. If you’re
looking to master pointers, especially how they work with data structures, the C Programming
Course Online with Data Structures offers a comprehensive breakdown of this concept.

Syntax of C Pointers
The syntax of pointers is similar to the variable declaration in C, but we use the ( * )
dereferencing operator in the pointer declaration.
datatype *ptr;
where
 ptr is the name of the pointer.
 datatype is the type of data it is pointing to.
The above syntax is used to define a pointer to a variable. We can also define pointers to
functions, structures, etc.

How to Use Pointers?


The use of pointers in C can be divided into three steps:
1. Pointer Declaration
2. Pointer Initialization
3. Pointer Dereferencing

1. Pointer Declaration
In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer,
we use the ( * ) dereference operator before its name.
Example
int *ptr;
The pointer declared here will point to some random memory address as it is not initialized. Such
pointers are called wild pointers.

2. Pointer Initialization
Pointer initialization is the process where we assign some initial value to the pointer variable. We
generally use the ( &: ampersand ) addressof operator to get the memory address of a variable
and then store it in the pointer variable.
Example
int var = 10;
int * ptr;
ptr = &var;
We can also declare and initialize the pointer in a single step. This method is called pointer
definition as the pointer is declared and initialized at the same time.
Example
int *ptr = &var;
Note: It is recommended that the pointers should always be initialized to some value before
starting using it. Otherwise, it may lead to number of errors.

3. Pointer Dereferencing
Dereferencing a pointer is the process of accessing the value stored in the memory address
specified in the pointer. We use the same ( * ) dereferencing operator that we used in the
pointer declaration.
Dereferencing a Pointer in C

C Pointer Example

// C program to illustrate Pointers


#include<stdio.h>

voidgeeks()
{
intvar=10;

// declare pointer variable


int*ptr;

// note that data type of ptr and var must be same


ptr=&var;

// assign the address of a variable to a pointer


printf("Value at ptr = %p \n",ptr);
printf("Value at var = %d \n",var);
printf("Value at *ptr = %d \n",*ptr);
}

// Driver program
intmain()
{
geeks();
return0;
}

Output

Value at ptr = 0x7ffca84068dc


Value at var = 10
Value at *ptr = 10

Types of Pointers in C
Pointers in C can be classified into many different types based on the parameter on which we are
defining their types. If we consider the type of variable stored in the memory location pointed by
the pointer, then the pointers can be classified into the following types:

1. Integer Pointers
As the name suggests, these are the pointers that point to the integer values.
Syntax
int *ptr;

These pointers are pronounced as Pointer to Integer.


Similarly, a pointer can point to any primitive data type. It can point also point to derived data
types such as arrays and user-defined data types such as structures.

2. Array Pointer
Pointers and Array are closely related to each other. Even the array name is the pointer to its first
element. They are also known as Pointer to Arrays. We can create a pointer to an array using the
given syntax.
Syntax
char *ptr = &array_name;

Pointer to Arrays exhibits some interesting properties which we discussed later in this article.

. Structure Pointer
The pointer pointing to the structure type is called Structure Pointer or Pointer to Structure. It can
be declared in the same way as we declare the other primitive data types.
Syntax
struct struct_name *ptr;

In C, structure pointers are used in data structures such as linked lists, trees, etc.

4. Function Pointers
Function pointers point to the functions. They are different from the rest of the pointers in the
sense that instead of pointing to the data, they point to the code. Let’s consider a function
prototype – int func (int, char), the function pointer for this function will be
Syntax
int (*ptr)(int, char);

Note: The syntax of the function pointers changes according to the function prototype.
5. Double Pointers
In C language, we can define a pointer that stores the memory address of another pointer. Such
pointers are called double-pointers or pointers-to-pointer. Instead of pointing to a data value,
they point to another pointer.

Syntax
datatype ** pointer_name;

Dereferencing Double Pointer


*pointer_name; // get the address stored in the inner level pointer
**pointer_name; // get the value pointed by inner level pointer

Note: In C, we can create multi-level pointers with any number of levels such as – ***ptr3,
****ptr4, ******ptr5 and so on.

6. NULL Pointer
The Null Pointers are those pointers that do not point to any memory location. They can be
created by assigning a NULL value to the pointer. A pointer of any type can be assigned the
NULL value.
Syntax
data_type *pointer_name = NULL;
or
pointer_name = NULL

It is said to be good practice to assign NULL to the pointers currently not in use.

7. Void Pointer
The Void pointers in C are the pointers of type void. It means that they do not have any
associated data type. They are also called generic pointers as they can point to any type and can
be typecasted to any type.
Syntax
void * pointer_name;

One of the main properties of void pointers is that they cannot be dereferenced.

8. Wild Pointers
The Wild Pointers are pointers that have not been initialized with something yet. These types of
C-pointers can cause problems in our programs and can eventually cause them to crash. If values
is updated using wild pointers, they could cause data abort or data corruption.
Example
int *ptr;
char *str;
9. Constant Pointers
In constant pointers, the memory address stored inside the pointer is constant and cannot be
modified once it is defined. It will always point to the same memory address.
Syntax
data_type * const pointer_name;

10. Pointer to Constant


The pointers pointing to a constant value that cannot be modified are called pointers to a
constant. Here we can only access the data pointed by the pointer, but cannot modify it.
Although, we can change the address stored in the pointer to constant.
Syntax
const data_type * pointer_name;

Other Types of Pointers in C:


There are also the following types of pointers available to use in C apart from those specified
above:
 Far pointer: A far pointer is typically 32-bit that can access memory outside the current
segment.
 Dangling pointer: A pointer pointing to a memory location that has been deleted (or freed) is
called a dangling pointer.
 Huge pointer: A huge pointer is 32-bit long containing segment address and offset address.
 Complex pointer: Pointers with multiple levels of indirection.
 Near pointer: Near pointer is used to store 16-bit addresses means within the current segment
on a 16-bit machine.
 Normalized pointer: It is a 32-bit pointer, which has as much of its value in the segment
register as possible.
 File Pointer: The pointer to a FILE data type is called a stream pointer or a file pointer.

Size of Pointers in C
The size of the pointers in C is equal for every pointer type. The size of the pointer does not
depend on the type it is pointing to. It only depends on the operating system and CPU
architecture. The size of pointers in C is
 8 bytes for a 64-bit System
 4 bytes for a 32-bit System
The reason for the same size is that the pointers store the memory addresses, no matter what type
they are. As the space required to store the addresses of the different memory locations is the
same, the memory required by one pointer type will be equal to the memory required by other
pointer types.
How to find the size of pointers in C?
We can find the size of pointers using the sizeof operator as shown in the following program:
Example: C Program to find the size of different pointer types.
// C Program to find the size of different pointers types
#include<stdio.h>

// dummy structure
structstr{
};

// dummy function
voidfunc(inta,intb){};

intmain()
{
// dummy variables definitions
inta=10;
charc='G';
structstrx;

// pointer definitions of different types


int*ptr_int=&a;
char*ptr_char=&c;
structstr*ptr_str=&x;
void(*ptr_func)(int,int)=&func;
void*ptr_vn=NULL;

// printing sizes
printf("Size of Integer Pointer \t:\t%d bytes\n",
sizeof(ptr_int));
printf("Size of Character Pointer\t:\t%d bytes\n",
sizeof(ptr_char));
printf("Size of Structure Pointer\t:\t%d bytes\n",
sizeof(ptr_str));
printf("Size of Function Pointer\t:\t%d bytes\n",
sizeof(ptr_func));
printf("Size of NULL Void Pointer\t:\t%d bytes",
sizeof(ptr_vn));

return0;
}

Output

Size of Integer Pointer : 8 bytes


Size of Character Pointer : 8 bytes
Size of Structure Pointer : 8 bytes
Size of Function Pointer : 8 bytes
Size of NULL Void Pointer : 8 bytes
As we can see, no matter what the type of pointer it is, the size of each and every pointer is the
same.
Now, one may wonder that if the size of all the pointers is the same, then why do we need to
declare the pointer type in the declaration? The type declaration is needed in the pointer for
dereferencing and pointer arithmetic purposes.

C Pointer Arithmetic
The Pointer Arithmetic refers to the legal or valid arithmetic operations that can be performed on
a pointer. It is slightly different from the ones that we generally use for mathematical
calculations as only a limited set of operations can be performed on pointers. These operations
include:
 Increment in a Pointer
 Decrement in a Pointer
 Addition of integer to a pointer
 Subtraction of integer to a pointer
 Subtracting two pointers of the same type
 Comparison of pointers of the same type.
 Assignment of pointers of the same type.
C

// C program to illustrate Pointer Arithmetic

#include<stdio.h>

intmain()
{

// Declare an array
intv[3]={10,100,200};

// Declare pointer variable


int*ptr;

// Assign the address of v[0] to ptr


ptr=v;

for(inti=0;i<3;i++){

// print value at address which is stored in ptr


printf("Value of *ptr = %d\n",*ptr);

// print value of ptr


printf("Value of ptr = %p\n\n",ptr);

// Increment pointer ptr by 1


ptr++;
}
return0;
}

Output

Value of *ptr = 10
Value of ptr = 0x7ffcfe7a77a0

Value of *ptr = 100


Value of ptr = 0x7ffcfe7a77a4

Value of *ptr = 200


Value of ptr = 0x7ffcfe7a77a8

C Pointers and Arrays


In C programming language, pointers and arrays are closely related. An array name acts like a
pointer constant. The value of this pointer constant is the address of the first element. For
example, if we have an array named val then val and &val[0] can be used interchangeably.
If we assign this value to a non-constant pointer of the same type, then we can access the
elements of the array using this pointer.
Example 1: Accessing Array Elements using Pointer with Array Subscript

// C Program to access array elements using pointer


#include<stdio.h>

Void fun()
{
// Declare an array
intval[3]={5,10,15};

// Declare pointer variable


int*ptr;

// Assign address of val[0] to ptr.


// We can use ptr=&val[0];(both are same)
ptr=val;
printf("Elements of the array are: ");

printf("%d, %d, %d",ptr[0],ptr[1],ptr[2]);

return;
}

// Driver program
intmain()
{
fun();
return0;
}

Output

Elements of the array are: 5, 10, 15

Not only that, as the array elements are stored continuously, we can pointer arithmetic operations
such as increment, decrement, addition, and subtraction of integers on pointer to move between
array elements.
Example 2: Accessing Array Elements using Pointer Arithmetic

// C Program to access array elements using pointers


#include<stdio.h>

intmain()
{

// defining array
intarr[5]={1,2,3,4,5};

// defining the pointer to array


int*ptr_arr=arr;

// traversing array using pointer arithmetic


for(inti=0;i<5;i++){
printf("%d ",*ptr_arr++);
}
return0;
}

Output

12345

This concept is not limited to the one-dimensional array, we can refer to a multidimensional
array element as well using pointers.
To know more about pointers to an array, refer to this article – Pointer to an Array

Uses of Pointers in C

The C pointer is a very powerful tool that is widely used in C programming to perform various
useful operations. It is used to achieve the following functionalities in C:
1. Pass Arguments by Reference
2. Accessing Array Elements
3. Return Multiple Values from Function
4. Dynamic Memory Allocation
5. Implementing Data Structures
6. In System-Level Programming where memory addresses are useful.
7. In locating the exact value at some memory location.
8. To avoid compiler confusion for the same variable name.
9. To use in Control Tables.

Advantages of Pointers
Following are the major advantages of pointers in C:
 Pointers are used for dynamic memory allocation and deallocation.
 An Array or a structure can be accessed efficiently with pointers
 Pointers are useful for accessing memory locations.
 Pointers are used to form complex data structures such as linked lists, graphs, trees, etc.
 Pointers reduce the length of the program and its execution time as well.

Disadvantages of Pointers

Pointers are vulnerable to errors and have following disadvantages:


 Memory corruption can occur if an incorrect value is provided to pointers.
 Pointers are a little bit complex to understand.
 Pointers are majorly responsible for memory leaks in C.
 Pointers are comparatively slower than variables in C.
 Uninitialized pointers might cause a segmentation fault.
File Handling in C



File handling in C is the process in which we create, open, read, write, and close operations on
a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(),
fprintf(), etc. to perform input, output, and many different C file operations in our program.

Why do we need File Handling in C?


So far the operations using the C program are done on a prompt/terminal which is not stored
anywhere. The output is deleted when the program is closed. But in the software industry, most
programs are written to store the information fetched from the program. The use of file
handling is exactly what the situation calls for.
In order to understand why file handling is important, let us look at a few features of using
files:
 Reusability: The data stored in the file can be accessed, updated, and deleted anywhere
and anytime providing high reusability.
 Portability: Without losing any data, files can be transferred to another in the computer
system. The risk of flawed coding is minimized with this feature.
 Efficient: A large amount of input may be required for some programs. File handling
allows you to easily access a part of a file using few instructions which saves a lot of time
and reduces the chance of errors.
 Storage Capacity: Files allow you to store a large amount of data without having to worry
about storing everything simultaneously in a program.
If you’re interested in working with files and integrating them into larger data structures, the C
Programming Course Online with Data Structures provides detailed lessons on file
management in C.

Types of Files in C
A file can be classified into two types based on the way the file stores the data. They are as
follows:
 Text Files
 Binary Files

1. Text Files
A text file contains data in the form of ASCII characters and is generally used to store a
stream of characters.
 Each line in a text file ends with a new line character (‘\n’).
 It can be read or written by any text editor.
 They are generally stored with .txt file extension.
 Text files can also be used to store the source code.
2. Binary Files
A binary file contains data in binary form (i.e. 0’s and 1’s) instead of ASCII characters. They
contain data that is stored in a similar manner to how it is stored in the main memory.
 The binary files can be created only from within a program and their contents can only be
read by a program.
 More secure as they are not easily readable.
 They are generally stored with .bin file extension.

C File Operations
C file operations refer to the different possible operations that we can perform on a file in C
such as:
1. Creating a new file – fopen() with attributes as “a” or “a+” or “w” or “w+”
2. Opening an existing file – fopen()
3. Reading from file – fscanf() or fgets()
4. Writing to a file – fprintf() or fputs()
5. Moving to a specific location in a file – fseek(), rewind()
6. Closing a file – fclose()
The highlighted text mentions the C function used to perform the file operations.

Functions for C File Operations

File Pointer in C
A file pointer is a reference to a particular position in the opened file. It is used in file handling
to perform all file operations such as read, write, close, etc. We use the FILE macro to declare
the file pointer variable. The FILE macro is defined inside <stdio.h> header file.

Syntax of File Pointer


FILE*pointer_name;
File Pointer is used in almost all the file operations in C.

Open a File in C
For opening a file in C, the fopen() function is used with the filename or file path along with
the required access modes.

Syntax of fopen()
FILE* fopen(const char *file_name, const char *access_mode);

Parameters
 file_name: name of the file when present in the same directory as the source file.
Otherwise, full path.
 access_mode: Specifies for what operation the file is being opened.
Return Value
 If the file is opened successfully, returns a file pointer to it.
 If the file is not opened, then returns NULL.

File opening modes in C


File opening modes or access modes specify the allowed operations on the file to be opened.
They are passed as an argument to the fopen() function. Some of the commonly used file
access modes are listed below:

Opening
Modes Description

Searches file. If the file is opened successfully fopen( ) loads it into memory and
r sets up a pointer that points to the first character in it. If the file cannot be opened
fopen( ) returns NULL.

Open for reading in binary mode. If the file does not exist, fopen( ) returns
rb
NULL.

w Open for writing in text mode. If the file exists, its contents are overwritten. If the
Opening
Modes Description

file doesn’t exist, a new file is created. Returns NULL, if unable to open the file.

Open for writing in binary mode. If the file exists, its contents are overwritten. If
wb
the file does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into memory and
sets up a pointer that points to the last character in it. It opens only in the append
a
mode. If the file doesn’t exist, a new file is created. Returns NULL, if unable to
open the file.

Open for append in binary mode. Data is added to the end of the file. If the file
ab
does not exist, it will be created.

Searches file. It is opened successfully fopen( ) loads it into memory and sets up a
r+ pointer that points to the first character in it. Returns NULL, if unable to open the
file.

Open for both reading and writing in binary mode. If the file does not exist,
rb+
fopen( ) returns NULL.

Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist
w+
a new file is created. Returns NULL, if unable to open the file.

Open for both reading and writing in binary mode. If the file exists, its contents
wb+
are overwritten. If the file does not exist, it will be created.

a+ Searches file. If the file is opened successfully fopen( ) loads it into memory and
sets up a pointer that points to the last character in it. It opens the file in both
Opening
Modes Description

reading and append mode. If the file doesn’t exist, a new file is created. Returns
NULL, if unable to open the file.

Open for both reading and appending in binary mode. If the file does not exist, it
ab+
will be created.

As given above, if you want to perform operations on a binary file, then you have to append ‘b’
at the last. For example, instead of “w”, you have to use “wb”, instead of “a+” you have to use
“a+b”.
Example of Opening a File
C

// C Program to illustrate file opening


#include<stdio.h>
#include<stdlib.h>

intmain()
{
// file pointer variable to store the value returned by
// fopen
FILE*fptr;

// opening the file in read mode


fptr=fopen("filename.txt","r");

// checking if the file is opened successfully


if(fptr==NULL){
printf("The file is not opened. The program will "
"now exit.");
exit(0);
}

return0;
}

Output

The file is not opened. The program will now exit.


The file is not opened because it does not exist in the source directory. But the fopen() function
is also capable of creating a file if it does not exist. It is shown below

Create a File in C
The fopen() function can not only open a file but also can create a file if it does not exist
already. For that, we have to use the modes that allow the creation of a file if not found such as
w, w+, wb, wb+, a, a+, ab, and ab+.
FILE *fptr;
fptr = fopen("filename.txt", "w");
Example of Opening a File
C

// C Program to create a file


#include<stdio.h>
#include<stdlib.h>

intmain()
{
// file pointer
FILE*fptr;

// creating file using fopen() access mode "w"


fptr=fopen("file.txt","w");

// checking if the file is created


if(fptr==NULL){
printf("The file is not opened. The program will "
"exit now");
exit(0);
}
else{
printf("The file is created Successfully.");
}

return0;
}

Output

The file is created Successfully.


Reading From a File
The file read operation in C can be performed using functions fscanf() or fgets(). Both the
functions performed the same operations as that of scanf and gets but with an additional
parameter, the file pointer. There are also other functions we can use to read from a file. Such
functions are listed below:
Function Description

fscanf() Use formatted string and variable arguments list to take input from a file.

fgets() Input the whole line from the file.

fgetc() Reads a single character from the file.

fgetw() Reads a number from a file.

fread() Reads the specified bytes of data from a binary file.

So, it depends on you if you want to read the file line by line or character by character.
Example:
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);
The getc() and some other file reading functions return EOF (End Of File) when they reach the
end of the file while reading. EOF indicates the end of the file and its value is implementation-
defined.
Note: One thing to note here is that after reading a particular part of the file, the file pointer
will be automatically moved to the end of the last read character.
Write to a File
The file write operations can be performed by the functions fprintf() and fputs() with
similarities to read operations. C programming also provides some other functions that can be
used to write data to a file such as:
Function Description

Similar to printf(), this function use formatted string and varible arguments list to
fprintf()
print output to the file.

fputs() Prints the whole line in the file and a newline at the end.
Function Description

fputc() Prints a single character into the file.

fputw() Prints a number to the file.

fwrite() This functions write the specified amount of bytes to the binary file.

Example:
FILE *fptr ;
fptr = fopen(“fileName.txt”, “w”);
fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);
fputc("a", fptr);

Closing a File
The fclose() function is used to close the file. After successful file operations, you must always
close a file to remove it from the memory.
Syntax of fclose()
fclose(file_pointer);
where the file_pointer is the pointer to the opened file.

Example:
FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(fptr);

Examples of File Handing in C


Example 1: Program to Create a File, Write in it, And Close the File
C

// C program to Open a File,


// Write in it, And Close the File
#include<stdio.h>
#include<string.h>

intmain()
{

// Declare the file pointer


FILE*filePointer;

// Get the data to be written in file


chardataToBeWritten[50]="data structure-A Computer "
"Science Portal for Geeks";

// Open the existing file GfgTest.c using fopen()


// in write mode using "w" attribute
filePointer=fopen("GfgTest.c","w");

// Check if this filePointer is null


// which maybe if the file does not exist
if(filePointer==NULL){
printf("GfgTest.c file failed to open.");
}
else{

printf("The file is now opened.\n");

// Write the dataToBeWritten into the file


if(strlen(dataToBeWritten)>0){

// writing in the file using fputs()


fputs(dataToBeWritten,filePointer);
fputs("\n",filePointer);
}

// Closing the file using fclose()


fclose(filePointer);

printf("Data successfully written in file "


"GfgTest.c\n");
printf("The file is now closed.");
}

return0;
}

Output

The file is now opened.


Data successfully written in file GfgTest.c
The file is now closed.
This program will create a file named GfgTest.c in the same directory as the source file which
will contain the following text: “GeeksforGeeks-A Computer Science Portal for Geeks”.
Example 2: Program to Open a File, Read from it, And Close the File
C

// C program to Open a File,


// Read from it, And Close the File
#include<stdio.h>
#include<string.h>

intmain()
{

// Declare the file pointer


FILE*filePointer;

// Declare the variable for the data to be read from


// file
chardataToBeRead[50];

// Open the existing file GfgTest.c using fopen()


// in read mode using "r" attribute
filePointer=fopen("GfgTest.c","r");

// Check if this filePointer is null


// which maybe if the file does not exist
if(filePointer==NULL){
printf("GfgTest.c file failed to open.");
}
else{

printf("The file is now opened.\n");

// Read the dataToBeRead from the file


// using fgets() method
while(fgets(dataToBeRead,50,filePointer)
!=NULL){

// Print the dataToBeRead


printf("%s",dataToBeRead);
}

// Closing the file using fclose()


fclose(filePointer);

printf(
"Data successfully read from file GfgTest.c\n");
printf("The file is now closed.");
}
return0;
}

Output
The file is now opened.
GeeksforGeeks-A Computer Science Portal for Geeks
Data successfully read from file GfgTest.c
The file is now closed.

This program reads the text from the file named GfgTest.c which we created in the previous
example and prints it in the console.

Read and Write in a Binary File


Till now, we have only discussed text file operations. The operations on a binary file are
similar to text file operations with little difference.

Opening a Binary File


To open a file in binary mode, we use the rb, rb+, ab, ab+, wb, and wb+ access mode in the
fopen() function. We also use the .bin file extension in the binary filename.
Example
fptr = fopen("filename.bin", "rb");

Write to a Binary File


We use fwrite() function to write data to a binary file. The data is written to the binary file in
the from of bits (0’s and 1’s).

Syntax of fwrite()
size_tfwrite(const void *ptr, size_tsize, size_tnmemb, FILE *file_pointer);
Parameters:
 ptr: pointer to the block of memory to be written.
 size: size of each element to be written (in bytes).
 nmemb: number of elements.
 file_pointer: FILE pointer to the output file stream.
Return Value:
 Number of objects written.
Example: Program to write to a Binary file using fwrite()
C

// C program to write to a Binary file using fwrite()


#include<stdio.h>
#include<stdlib.h>
structthreeNum{
intn1,n2,n3;
};
intmain()
{
intn;
// Structure variable declared here.
structthreeNumnum;
FILE*fptr;
if((fptr=fopen("C:\\program.bin","wb"))==NULL){
printf("Error! opening file");
// If file pointer will return NULL
// Program will exit.
exit(1);
}
intflag=0;
// else it will return a pointer to the file.
for(n=1;n<5;++n){
num.n1=n;
num.n2=5*n;
num.n3=5*n+1;
flag=fwrite(&num,sizeof(structthreeNum),1,
fptr);
}

// checking if the data is written


if(!flag){
printf("Write Operation Failure");
}
else{
printf("Write Operation Successful");
}

fclose(fptr);

return0;
}

Output

Write Operation Successful


Reading from Binary File
The fread() function can be used to read data from a binary file in C. The data is read from the
file in the same form as it is stored i.e. binary form.
Syntax of fread()
size_tfread(void *ptr, size_tsize, size_tnmemb, FILE *file_pointer);
Parameters:
 ptr: pointer to the block of memory to read.
 size: the size of each element to read(in bytes).
 nmemb: number of elements.
 file_pointer: FILE pointer to the input file stream.

Return Value:
 Number of objects written.
Example: Program to Read from a binary file using fread()
C

// C Program to Read from a binary file using fread()


#include<stdio.h>
#include<stdlib.h>
structthreeNum{
intn1,n2,n3;
};
intmain()
{
intn;
structthreeNumnum;
FILE*fptr;
if((fptr=fopen("C:\\program.bin","rb"))==NULL){
printf("Error! opening file");
// If file pointer will return NULL
// Program will exit.
exit(1);
}
// else it will return a pointer to the file.
for(n=1;n<5;++n){
fread(&num,sizeof(structthreeNum),1,fptr);
printf("n1: %d\tn2: %d\tn3: %d\n",num.n1,num.n2,
num.n3);
}
fclose(fptr);

return0;
}

Output
n1: 1 n2: 5 n3: 6
n1: 2 n2: 10 n3: 11
n1: 3 n2: 15 n3: 16
n1: 4 n2: 20 n3: 21

fseek() in C
If we have multiple records inside a file and need to access a particular record that is at a
specific position, so we need to loop through all the records before it to get the record. Doing
this will waste a lot of memory and operational time. To reduce memory consumption and
operational time we can use fseek() which provides an easier way to get to the required data.
fseek() function in C seeks the cursor to the given record in the file.
Syntax for fseek()
int fseek(FILE *ptr, long int offset, int pos);
Example of fseek()

// C Program to demonstrate the use of fseek() in C


#include<stdio.h>

intmain()
{
FILE*fp;
fp=fopen("test.txt","r");

// Moving pointer to end


fseek(fp,0,SEEK_END);

// Printing position of pointer


printf("%ld",ftell(fp));

return0;
}

Output
81

rewind() in C
The rewind() function is used to bring the file pointer to the beginning of the file. It can be
used in place of fseek() when you want the file pointer at the start.
Syntax of rewind()
rewind (file_pointer);

Example

// C program to illustrate the use of rewind


#include<stdio.h>

intmain()
{
FILE*fptr;
fptr=fopen("file.txt","w+");
fprintf(fptr,"data structures\n");

// using rewind()
rewind(fptr);
// reading from file
charbuf[50];
fscanf(fptr,"%[^\n]s",buf);

printf("%s",buf);

return0;
}

Output:

Data structures

More Functions for C File Operations


The following table lists some more functions that can be used to perform file operations or
assist in performing them.
Functions Description

fopen() It is used to create a file or to open a file.

fclose() It is used to close a file.

fgets() It is used to read a file.

fprintf() It is used to write blocks of data into a file.

fscanf() It is used to read blocks of data from a file.

getc() It is used to read a single character to a file.

putc() It is used to write a single character to a file.


Functions Description

fseek() It is used to set the position of a file pointer to a mentioned location.

ftell() It is used to return the current position of a file pointer.

rewind() It is used to set the file pointer to the beginning of a file.

putw() It is used to write an integer to a file.

getw() It is used to read an integer from a file.

You might also like