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

Unit 1

Uploaded by

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

Unit 1

Uploaded by

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

21CSC201J – Data Structures

and Algorithms
Unit – 1 : Session – 9 : SLO-2

SRMInstitute of ScienceandTechnology 1
Time-Space Trade-Off in Algorithms.

A tradeoff is a situation where one thing increases and another thing decreases. It is a
way to solve a problem in:

Either in less time and by using more space, or In very little space by spending a long
amount of time.

Types of Space-Time Trade-off

Compressed or Uncompressed data


Re Rendering or Stored images
Smaller code or loop unrolling
Lookup tables or Recalculation

SRMInstitute of ScienceandTechnology 2
Compressed or Uncompressed data

A space-time trade-off can be applied to the problem of data storage. If


data stored is uncompressed, it takes more space but less time. But if the
data is stored compressed, it takes less space but more time to run the
decompression algorithm. There are many instances where it is possible
to directly work with compressed data. In that case of compressed
bitmap indices, where it is faster to work with compression than without
compression.

Re-Rendering or Stored images:

In this case, storing only the source and rendering it as an image would
take more space but less time i.e., storing an image in the cache is faster
than re-rendering but requires more space in memory.

SRMInstitute of ScienceandTechnology 3
Smaller code or Loop Unrolling

Smaller code occupies less space in memory but it requires high computation
time that is required for jumping back to the beginning of the loop at the end
of each iteration. Loop unrolling can optimize execution speed at the cost of
increased binary size. It occupies more space in memory but requires less
computation time.

Lookup tables or Recalculation:


In a lookup table, an implementation can include the entire table which
reduces computing time but increases the amount of memory needed. It can
recalculate i.e., compute table entries as needed, increasing computing time
but reducing memory requirements.

SRMInstitute of ScienceandTechnology 4
21CSC201J – Data Structures
and Algorithms
Unit – 1 : Session – 8 : SLO-2

SRMInstitute of ScienceandTechnology 1
BIG Ω NOTATION(Ω ): Ω notation provides an asymptotic lower bound.
Ω(g(n)) = { f(n): there exist positive constants c and n0 such that 0 ≤ cg(n)
≤ f(n) for all n≥ n0}

SRMInstitute of ScienceandTechnology 2
Θ NOTATION: Θ((g(n)) = {f(n): there exist positive constants c1, c2
and n0 such that 0 ≤ c1*g(n) ≤ f(n) ≤ c2*g(n) for all n≥n0}

SRMInstitute of ScienceandTechnology 3
21CSC201J – Data Structures
and Algorithms
Unit – 1 : Session – 8: SLO-1

SRMInstitute of ScienceandTechnology 1
MATHEMATICAL NOTATION

Asymptotic analysis refers to computing the running time of any


operation in mathematical units of computation.

Ο Notation
Ω Notation
θ Notation
There are 3 types of asymptotic notations:

• Big O notation
• Ω notation
• θ notation

SRMInstitute of ScienceandTechnology 2
Big Oh Notation, Ο It measures the worst case time complexity or
longest amount of time an algorithm can possibly take to complete.

O(g(n)) = { f(n): there exist positive constants c and n0 such that 0 <=
f(n) <= cg(n) for all n >= n0}

SRMInstitute of ScienceandTechnology 3
21CSC201J – Data Structures
and Algorithms
Unit – 1 : Session – 9 : SLO-1

SRMInstitute of ScienceandTechnology 1
Time and Space Complexity

ANALYSIS OF BEST ,WORST AND AVERAGE CASE

Algorithm Analysis An algorithm is said to be efficient and fast, if it takes


less time to execute consumes less memory space.

The performance of an algorithm is measured on the basis of

1. Time Complexity

2. 2. Space Complexity

SRMInstitute of ScienceandTechnology 2
Space Complexity

The amount of memory space required by the algorithm in its life cycle. A
fixed part : For example simple variables & constant used and program
size etc. A variable part : For example dynamic memory allocation,
recursion stacks space etc.

Space complexity S(P) of any algorithm P is S(P) = C + SP(I) Where C is


the fixed part S(I) is the variable part of the algorithm

SRMInstitute of ScienceandTechnology 3
Time Complexity - T(n)

The amount of time required by the algorithm to run to completion. T(n) can
be measured as the number of steps, provided each step consumes
constant time.

ALGORITHM ANALYSIS

The worst-case complexity of the algorithm is the function defined by the


maximum number of steps taken on any instance of size n.

The best-case complexity of the algorithm is the function defined by the


minimum number of steps taken on any instance of size n.

Finally, the average-case complexity of the algorithm is the function defined


by the average number of steps taken on any instance of size n.

SRMInstitute of ScienceandTechnology 4
18CSC201J – Data Structures
and Algorithms

Unit – 1 : Session – 3 : SLO - 2


A structure pointer is defined as the pointer which points to the
address of the memory block that stores a structure known as the
structure pointer.
Complex data structures like Linked lists, trees, graphs, etc. are
created with the help of structure pointers.
The structure pointer tells the address of a structure in memory by
pointing the variable to the structure variable.
// C program to demonstrate structure
pointer
#include <stdio.h>

struct point {
int value;
};

int main()
{

struct point s;

// Initialization of the structure


pointer
struct point* ptr = &s;

return 0;
}

In the above code s is an instance of struct point and ptr is the struct pointer because it is storing the address of
struct point.
Accessing the Structure Member with the Help of Pointers

There are two ways to access the members of the structure with the help of a structure pointer:
With the help of (*) asterisk or indirection operator and (.) dot operator.
With the help of ( -> ) Arrow operator.
Below is the program to access the structure members using the structure pointer with the help of the dot operator.
#include <stdio.h>
#include <string.h>
struct Student {
int roll_no;
char name[30];
char branch[40];
int batch;
};
int main()
{
struct Student s1; struct Student* ptr = &s1;
s1.roll_no = 27;
strcpy(s1.name, "Kamlesh Joshi");
strcpy(s1.branch, "Computer Science And Engineering");
s1.batch = 2019;
printf("Roll Number: %d\n", (*ptr).roll_no);
printf("Name: %s\n", (*ptr).name);
printf("Branch: %s\n", (*ptr).branch);
printf("Batch: %d", (*ptr).batch); return 0;
}
Output:
1
Below is the program to access the structure members using the structure pointer with the help of the Arrow operator.
In this program, we have created a Structure Student containing structure variable s. The Structure Student has
roll_no, name, branch, and batch.

#include <stdio.h>
#include <string.h>
struct Student {

int roll_no;
char name[30];
char branch[40];
int batch;
};
struct Student s, *ptr;
int main()
{
ptr = &s;
printf("Enter the Roll Number of Student\n"); scanf("%d", &ptr->roll_no);
printf("Enter Name of Student\n"); scanf("%s", &ptr->name);
printf("Enter Branch of Student\n"); scanf("%s", &ptr->branch);
printf("Enter batch of Student\n"); scanf("%d", &ptr->batch);
printf("\nStudent details are: \n");
printf("Roll No: %d\n", ptr->roll_no);
printf("Name: %s\n", ptr->name);
printf("Branch: %s\n", ptr->branch);
printf("Batch: %d\n", ptr->batch);
return 0;
}
Output:
Enter the Roll Number of Student
27
Enter Name of Student
Kamlesh_Joshi
Enter Branch of Student
Computer_Science_And_Engineering
Enter batch of Student
2019
Student details are:
Roll No: 27
Name: Kamlesh_Joshi
Branch: Computer_Science_And_Engineering
18CSC201J – Data Structures
and Algorithms

Unit – 1 : Session – 3 : SLO - 2


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 geeks()
{
// Declare an array
int val[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
int main()
{
geeks();
OutputElements of the array are: 5 10 15
return 0;
}
18CSC201J – Data Structures and
Algorithms
Unit – 1 : Session – 2 : SLO - 2
The structure in C is a user-defined data type that can be used to group
items of possibly different types into a single type.
The struct keyword is used to define the structure in the C
programming language.
The items in the structure are called its member and they can be of any
valid data type.
C Structure Declaration
We have to declare structure in C before using it in our program.
In structure declaration, we specify its member variables along with their
datatype.
We can use the struct keyword to declare the structure in C using the following
syntax:

struct structure_name { data_type member_name1; data_type


member_name1; .... .... };
18CSC201J – Data Structures and
Algorithms
Unit – 1 : Session – 1 : SLO - 2
Primitive Data Types
Character Data Type
Character data type allows its variable to store only a single
character. The size of the character is 1 byte. It is the most
basic data type in C. It stores a single character and requires a
single byte of memory in almost all compilers.
 Range: (-128 to 127) or (0 to 255)
 Size: 1 byte
 Format Specifier: %c

Syntax of char

The char keyword is used to declare the variable of character


type:
char var_name;
// C program to print Integer data types.
#include <stdio.h>
int main()
{
char a = 'a';
char c;
printf("Value of a: %c\n", a);
a++;
printf("Value of a after increment is: %c\n", a);
// c is assigned ASCII values
// which corresponds to the
// character 'c'
// a-->97 b-->98 c-->99
// here c will be printed
c = 99;
printf("Value of c: %c", c);
return 0;
}
Output
Value of a: a
Value of a after increment is: b
Value of c: c
Float Data Type
In C programming float data type is used to store floating-
point values. Float in C is used to store decimal and
exponential values. It is used to store decimal numbers
(numbers with floating point values) with single precision.
 Range: 1.2E-38 to 3.4E+38
 Size: 4 bytes
 Format Specifier: %f

Syntax of float

The float keyword is used to declare the variable as a floating


point:
float var_name;
// C Program to demonstrate use
// of Floating types
#include <stdio.h>

int main()
{
float a = 9.0f;
float b = 2.5f;

// 2x10^-4
float c = 2E-4f;
printf("%f\n", a);
printf("%f\n", b);
printf("%f", c);
Output
9.000000
return 0;
2.500000
}
0.000200
Double Data Type
A Double data type in C is used to store decimal numbers (numbers with floating point
values) with double precision. It is used to define numeric values which hold numbers
with decimal values in C.
The double data type is basically a precision sort of data type that is capable of holding
64 bits of decimal numbers or floating points. Since double has more precision as
compared to that float then it is much more obvious that it occupies twice the memory
occupied by the floating-point type. It can easily accommodate about 16 to 17 digits after
or before a decimal point.
 Range: 1.7E-308 to 1.7E+308
 Size: 8 bytes
 Format Specifier: %lf

Syntax of Double

The variable can be declared as double precision floating point using the double
keyword:
double var_name;
// C Program to demonstrate
// use of double data type
#include <stdio.h>

int main()
{
double a = 123123123.00;
double b = 12.293123;
double c = 2312312312.123123;

printf("%lf\n", a);

printf("%lf\n", b);

printf("%lf", c);
Output
123123123.000000
return 0;
12.293123
}
2312312312.123123
Void Data Type
The void data type in C is used to specify that no value is present. It does not provide a
result value to its caller. It has no values and no operations. It is used to represent nothing.
Void is used in multiple ways as function return type, function arguments as void,
and pointers to void.
Syntax:
// function return type void

void exit(int check);

// Function without any parameter can accept void.

int print(void);

// memory allocation function which


// returns a pointer to void.
void *malloc (size_t size);
// C program to demonstrate
// use of void pointers
#include <stdio.h>

int main()
{
int val = 30;
void* ptr = &val;
printf("%d", *(int*)ptr);
return 0;
}Output
30
Size of Data Types in C // C Program to print size of

The size of the data types in C is dependent on // different data type in C

the size of the architecture, so we cannot define #include <stdio.h>


the universal size of the data types. For that, the int main()
C language provides the sizeof() operator to {
check the size of the data types. int size_of_int = sizeof(int);
int size_of_char = sizeof(char);

int size_of_float = sizeof(float);


int size_of_double = sizeof(double);
printf("The size of int data type : %d\n",
size_of_int);
printf("The size of char data type : %d\n",
Output
size_of_char);
The size of int data type : 4
printf("The size of float data type : %d\n",
The size of char data type : 1
size_of_float);
The size of float data type : 4 printf("The size of double data type : %d",
The size of double data type : 8 size_of_double);
return 0;
}
18CSC201J – Data Structures and
Algorithms
Unit – 1 : Session – 2 : SLO - 2
The structure in C is a user-defined data type that can be used to group items
of possibly different types into a single type.
The struct keyword is used to define the structure in the C programming
language.
The items in the structure are called its member and they can be of any valid
data type.
C Structure Declaration
We have to declare structure in C before using it in our program.
In structure declaration, we specify its member variables along with their
datatype.
We can use the struct keyword to declare the structure in C using the following
syntax:

struct structure_name { data_type member_name1; data_type


member_name1; .... .... };
18CSC201J – Data Structures and
Algorithms
Unit – 1 : Session – 1 : SLO - 1
Programming in C
The data types in C can be classified as follows:

Types Description

Primitive data types are the most basic data types that are
Primitive Data Types used for representing simple values such as integers, float,
characters, etc.

User Defined Data Types The user-defined data types are defined by the user himself.

The data types that are derived from the primitive or built-in
Derived Types
datatypes are referred to as Derived Data Types.
The following are some main primitive data types in C:
Integer Data Type
The integer datatype in C is used to store the whole numbers without decimal values. Octal values, hexadecimal
values, and decimal values can be stored in int data type in C.
• Range: -2,147,483,648 to 2,147,483,647
• Size: 4 bytes
• Format Specifier: %d

Syntax of Integer

We use int keyword to declare the integer variable:


int var_name;
The integer data type can also be used as
unsigned int: Unsigned int data type in C is used to store the data values from zero to positive numbers but it
can’t store negative values like signed int.
short int: It is lesser in size than the int by 2 bytes so can only store values from –32,768 to 32,767.
long int: Larger version of the int datatype so can store values greater than int.
unsigned short int: Similar in relationship with short int as unsigned int with int.
// C program to print Integer data types.
#include <stdio.h>
int main()
{
// Integer value with positive data.
int a = 9;
// integer value with negative data.
int b = -9;
// U or u is Used for Unsigned int in C.
int c = 89U;
// L or l is used for long int in C.
long int d = 99998L;
printf("Integer value with positive data: %d\n", a);
printf("Integer value with negative data: %d\n", b);
printf("Integer value with an unsigned int data: %u\n", c);
printf("Integer value with an long int data: %ld", d);
return 0;
}
Output
Integer value with positive data: 9
Integer value with negative data: -9
Integer value with an unsigned int data: 89
Integer value with an long int data: 99998
21CSC201J – Data Structures and
Algorithms
Unit – 1 : Session – 7: SLO -2

SRM Institute of Science and Technology 1


Queue ADT

The queue abstract data type (ADT) follows the basic design of the stack
abstract data type.

Each node contains a void pointer to the data and the link pointer to the
next element in the queue. The program’s responsibility is to allocate
memory for storing the data.

enqueue() – Insert an element at the end of the queue.

dequeue() – Remove and return the first element of the queue, if the
queue is not empty.

SRM Institute of Science and Technology 2


peek() – Return the element of the queue without removing it, if the
queue is not empty.

size() – Return the number of elements in the queue.

isEmpty() – Return true if the queue is empty, otherwise return false.

isFull() – Return true if the queue is full, otherwise return false.

SRM Institute of Science and Technology 3


Features of ADT:
Abstraction
Better Conceptualization
Robust
Encapsulation
Data Abstraction
Data Structure Independence:
Information Hiding
Modularity

Disadvantages:
Overhead
Complexity
Learning
Limited Flexibility
Cost

SRM Institute of Science and Technology 4


21CSC201J – Data Structures and
Algorithms
Unit – 1 : Session – 7 : SLO -1

SRM Institute of Science and Technology 1


1. List ADT

The List ADT Functions is given below:

get() – Return an element from the list at any given position.

insert() – Insert an element at any position of the list.

remove() – Remove the first occurrence of any element from a non-


empty list.

SRM Institute of Science and Technology 2


removeAt() – Remove the element at a specified location from a non-
empty list.

replace() – Replace an element at any position by another element.

size() – Return the number of elements in the list.

isEmpty() – Return true if the list is empty, otherwise return false.

isFull() – Return true if the list is full, otherwise return false.

SRM Institute of Science and Technology 3


2. Stack ADT
In Stack ADT Implementation instead of data being stored in each node,
the pointer to data is stored.

The program allocates memory for the data and address is passed to
the stack ADT.

The head node and the data nodes are encapsulated in the ADT. The
calling function can only see the pointer to the stack.

The stack head structure also contains a pointer to top and count of
number of entries currently in stack.

isEmpty() – Return true if the stack is empty, otherwise return false.

isFull() – Return true if the stack is full, otherwise return false.

SRM Institute of Science and Technology 4


push() – Insert an element at one end of the stack called top.

pop() – Remove and return the element at the top of the stack, if it
is not empty.

peek() – Return the element at the top of the stack without


removing it, if the stack is not empty.

size() – Return the number of elements in the stack.

SRM Institute of Science and Technology 5


21CSC201J – Data Structures and
Algorithms
Unit – 1 : Session – 6 : SLO -2

SRM Institute of Science and Technology 1


Abstract Data type (ADT)

Abstract Data type (ADT) is a type (or class) for objects whose behavior is
defined by a set of values and a set of operations.

The definition of ADT only mentions what operations are to be performed


but not how these operations will be implemented.

It does not specify how data will be organized in memory and what
algorithms will be used for implementing the operations.

It is called “abstract” because it gives an implementation-independent


view.

SRM Institute of Science and Technology 2


The process of providing only the essentials and hiding the details is
known as abstraction.

SRM Institute of Science and Technology 3


ADTs namely

List ADT,

Stack ADT,

Queue ADT.

SRM Institute of Science and Technology 4


21CSC201J – Data Structures and
Algorithms
Unit – 1 : Session – 6 : SLO -1

SRM Institute of Science and Technology 1


Data Structure Definition:

Data structures in C is a way of storing and organizing data


in the computer memory so that it can be processed efficiently.

Data structures can be broadly classified into two categories - Primtive


and Non-Primitive.

Non-primitive data structures can be further classified into two


categories - Linear and Non-linear.

SRM Institute of Science and Technology 2


21CSC201J – Data Structures and
Algorithms

Unit – 1 Session:5 SLO:2

SRM Institute of Science and Technology 1


Matrix multiplication in C

● Matrix multiplication in C: We can add, subtract, multiply and


divide 2 matrices. To do so, we are taking input from the user
for row number, column number, first matrix elements and
second matrix elements. Then we are performing
multiplication on the matrices entered by the user.
● In matrix multiplication first matrix one row element is
multiplied by second matrix all column elements.
● Let's try to understand the matrix multiplication of 2*2 and 3*3
matrices by the figure given below:
● matrix multiplication program in c
SRM Institute of Science and Technology 2
EXAMPLE

SRM Institute of Science and Technology


#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
} SRM Institute of Science and Technology
printf("multiply of the matrix=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
} SRM Institute of Science and Technology
Output:
enter the number of row=3
enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18

SRM Institute of Science and Technology


21CSC201J – Data Structures and
Algorithms

Unit – 1 Session:5 SLO:1

SRM Institute of Science and Technology 1


Matrix multiplication in C

● Matrix multiplication in C: We can add, subtract, multiply and


divide 2 matrices. To do so, we are taking input from the user
for row number, column number, first matrix elements and
second matrix elements. Then we are performing
multiplication on the matrices entered by the user.
● In matrix multiplication first matrix one row element is
multiplied by second matrix all column elements.
● Let's try to understand the matrix multiplication of 2*2 and 3*3
matrices by the figure given below:
● matrix multiplication program in c
SRM Institute of Science and Technology 2
EXAMPLE

SRM Institute of Science and Technology


#include<stdio.h>
#include<stdlib.h>
int main(){
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
system("cls");
printf("enter the number of row=");
scanf("%d",&r);
printf("enter the number of column=");
scanf("%d",&c);
printf("enter the first matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("enter the second matrix element=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&b[i][j]);
}
} SRM Institute of Science and Technology
printf("multiply of the matrix=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];
}
}
}
//for printing result
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d\t",mul[i][j]);
}
printf("\n");
}
return 0;
} SRM Institute of Science and Technology
Output:
enter the number of row=3
enter the number of column=3
enter the first matrix element=
111
222
333
enter the second matrix element=
111
222
333
multiply of the matrix=
666
12 12 12
18 18 18

SRM Institute of Science and Technology


21CSC201J – Data Structures and
Algorithms
Unit – 1 SESSION 4 SLO1
Dynamic Memory Allocation in C using malloc(), calloc(),
free() and realloc()

SRM Institute of Science and Technology 1


Matrix multiplication in C
Since C is a structured language, it has some fixed rules
for programming. One of them includes changing the size
of an array. An array is a collection of items stored at
contiguous memory locations.
arrays

SRM Institute of Science and Technology 2


As it can be seen that the length (size) of the array above
made is 9. But what if there is a requirement to change
this length (size). For Example,

If there is a situation where only 5 elements are needed to


be entered in this array. In this case, the remaining 4
indices are just wasting memory in this array. So there is
a requirement to lessen the length (size) of the array from
9 to 5.

SRM Institute of Science and Technology 3


malloc()
calloc()
free()
realloc()

SRM Institute of Science and Technology 4


C malloc() method

The “malloc” or “memory allocation” method in C is used


to dynamically allocate a single large block of memory
with the specified size. It returns a pointer of type void
which can be cast into a pointer of any form. It doesn’t
Initialize memory at execution time so that it has initialized
each block with the default garbage value initially.

Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size)
For Example:

ptr = (int*) malloc(100 * sizeof(int));


Since the size of int is 4 bytes, this statement will allocate
400 bytes of memory. And, the pointer ptr holds the
SRM Institute of Science and Technology 5
address of the first byte in the allocated memory.
MALLOC ()

SRM Institute of Science and Technology


FREE () AND REALLOC()

SRM Institute of Science and Technology


REALLOC( )
int main()
{
int index = 0, i = 0, n,
*marks; // this marks pointer hold the base address
// of the block created
int ans;
marks = (int*)malloc(sizeof(
int)); // dynamically allocate memory using malloc
// check if the memory is successfully allocated by
// malloc or not?
if (marks == NULL) {
printf("memory cannot be allocated");
}
else {
// memory has successfully allocated
printf("Memory has been successfully allocated by "
"using malloc\n");
printf("\n marks = %pc\n",
marks); // print the base or beginning
// address of allocated memory

SRM Institute of Science and Technology


REALLOC()

else {
printf("Memory has been successfully "
"reallocated using realloc:\n");
printf(
"\n base address of marks are:%pc",
marks); ////print the base or
///beginning address of
///allocated memory
}
}
} while (ans == 1);
// print the marks of the students
for (i = 0; i <= index; i++) {
printf("marks of students %d are: %d\n ", i,
marks[i]);
}
free(marks);
}
return 0;
}

SRM Institute of Science and Technology


21CSC201J – Data Structures and
Algorithms
Unit – 1 SESSION 4 SLO2
Dynamic Memory Allocation in C using malloc(), calloc(),
free() and realloc()

SRM Institute of Science and Technology 1


Matrix multiplication in C
Since C is a structured language, it has some fixed rules
for programming. One of them includes changing the size
of an array. An array is a collection of items stored at
contiguous memory locations.
arrays

SRM Institute of Science and Technology 2


As it can be seen that the length (size) of the array above
made is 9. But what if there is a requirement to change
this length (size). For Example,

If there is a situation where only 5 elements are needed to


be entered in this array. In this case, the remaining 4
indices are just wasting memory in this array. So there is
a requirement to lessen the length (size) of the array from
9 to 5.

SRM Institute of Science and Technology 3


malloc()
calloc()
free()
realloc()

SRM Institute of Science and Technology 4


C malloc() method

The “malloc” or “memory allocation” method in C is used


to dynamically allocate a single large block of memory
with the specified size. It returns a pointer of type void
which can be cast into a pointer of any form. It doesn’t
Initialize memory at execution time so that it has initialized
each block with the default garbage value initially.

Syntax of malloc() in C
ptr = (cast-type*) malloc(byte-size)
For Example:

ptr = (int*) malloc(100 * sizeof(int));


Since the size of int is 4 bytes, this statement will allocate
400 bytes of memory. And, the pointer ptr holds the
SRM Institute of Science and Technology 5
address of the first byte in the allocated memory.
MALLOC ()

SRM Institute of Science and Technology


FREE () AND REALLOC()

SRM Institute of Science and Technology


REALLOC( )
int main()
{
int index = 0, i = 0, n,
*marks; // this marks pointer hold the base address
// of the block created
int ans;
marks = (int*)malloc(sizeof(
int)); // dynamically allocate memory using malloc
// check if the memory is successfully allocated by
// malloc or not?
if (marks == NULL) {
printf("memory cannot be allocated");
}
else {
// memory has successfully allocated
printf("Memory has been successfully allocated by "
"using malloc\n");
printf("\n marks = %pc\n",
marks); // print the base or beginning
// address of allocated memory

SRM Institute of Science and Technology


REALLOC()

else {
printf("Memory has been successfully "
"reallocated using realloc:\n");
printf(
"\n base address of marks are:%pc",
marks); ////print the base or
///beginning address of
///allocated memory
}
}
} while (ans == 1);
// print the marks of the students
for (i = 0; i <= index; i++) {
printf("marks of students %d are: %d\n ", i,
marks[i]);
}
free(marks);
}
return 0;
}

SRM Institute of Science and Technology

You might also like