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

Problem Solving Techniques (PST)

Established under sub section (3) of Section 1 of Garden City University Act, 2013 (Karnataka Act No. 47 of 2013)

Dr. A P J Abdul Kalam School of Engineering


I Semester, B.Tech in Computer Science and Engineering (AI & ML, CS and DS)
Course Title: Problem Solving Techniques (PST) Course Code: 10ABTEC22114 Year: 2022-2023
Course Delivery Instructor: Ashwini S Date: 14/02/2023 Handout: 28

Arrays
Array in C can be defined as a method of clubbing multiple entities of similar type into a larger group. These entities
or elements can be of int, float, char, or double data type or can be of user-defined data types too like structures.
However, in order to be stored together in a single array, all the elements should be of the same data type. The
elements are stored from left to right with the left-most index being the 0th index and the rightmost index being the
(n-1) index.

 Array is a collection of elements of same data type.


 Elements are stored sequentially one after the other in memory.
 Each value in an array is reference by a single name, which is the name of the array and a subscript or index,
which indicates the position of the value in the array.
 The subscript is always a positive integer number, which is enclosed in a pair of square brackets.
 Example: int age [5];

Ashwini S, Assistant Professor Garden City University 1


Problem Solving Techniques (PST)

An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an
array for it.

How to declare an array?

For example,

Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning, it can hold 5 floating-point
values.

It's important to note that the size and type of an array cannot be changed once it is declared.

Access Array Elements:

 one can access elements of an array by indices.

 Suppose you declared an array mark as above. The first element is mark [0], the second element is mark[1]
and so on.

Ashwini S, Assistant Professor Garden City University 2


Problem Solving Techniques (PST)

Few keynotes:

 Arrays have 0 as the first index, not 1. In the above example, mark[0] is the first element.
 If the size of an array is n, to access the last element, the n-1 index is used. In this example, mark[4].
 Suppose the starting address of mark[0] is 2120d. Then, the address of the mark[1] will be 2124d. Similarly,
the address of mark[2] will be 2128d and so on.
 This is because the size of a float is 4 bytes.

Why Do We Need Arrays?


If we have a small number of elements, let us say we want 3 variables, then we can declare them separately like var1,
var2, and var3. But if we have a large number of variables then we can use arrays to store them.

Let us take a real-life example. Suppose you want to make a program that prints 1-100 digits. Now in C language, you
can achieve this by 2 methods. The first one is to make 100 variables and store the numbers from 1-100 in those
variables separately and then print each digit. The second method is to create an array of size 100 and store the
numbers in that array using a loop. These digits can be printed using a single loop in linear complexity. It is clear that
the second method is more optimized and desirable than the first one as it is more convenient to store these values in a
single array rather than creating 100 variables.

How to initialize an array?


It is possible to initialize an array during declaration. For example,

we can also initialize an array like this.

Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it with 5 elements.

Ashwini S, Assistant Professor Garden City University 3


Problem Solving Techniques (PST)

Here,

Example 1: Array Input/Output


// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array

#include <stdio.h>
int main()
{
int values[5];
printf("Enter 5 integers: ");

// taking input and storing it in an array

for(int i = 0; i < 5; ++i)


{
scanf("%d", &values[i]);
}
printf("Displaying integers: ");

// printing elements of an array

for(int i = 0; i < 5; ++i)


{
printf("%d\n", values[i]);
}
return 0;
}

Ashwini S, Assistant Professor Garden City University 4


Problem Solving Techniques (PST)

OUTPUT:
Enter 5 integers:
1
-3
34
0
3
Displaying integers:
1
-3
34
0
3

Ashwini S, Assistant Professor Garden City University 5


Established under sub section (3) of Section 1 of Garden City University Act, 2013 (Karnataka Act No. 47 of 2013)

Dr. A P J Abdul Kalam School of Engineering


I Semester, B.Tech in Computer Science and Engineering (AI & ML, CS and DS)
Course Title: Problem Solving Techniques (PST) Course Code: 10ABTEC22114 Year: 2022-2023
Course Delivery Instructor: Ashwini S Date: 21/02/2023 Handout: 29

Types of Arrays

Array in C are of two types; Single dimensional arrays(1D) and Multidimensional arrays (2D).

Single Dimensional Arrays: A One-Dimensional Array is the simplest form of an Array in which the elements
are stored linearly and can be accessed individually by specifying the index value of each element stored in the array.
Single dimensional array or 1-D array is the simplest form of arrays that can be found in C. This type of array consists
of elements of similar types and these elements can be accessed through their indices.

Declaration of Single Dimensional Array(1D):


// Program to find the average of n numbers using arrays

#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0;
double average;
printf("Enter number of elements: ");
scanf("%d", &n);
for(i=0; i < n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
// adding integers entered by the user to the sum variable
sum += marks[i];
}
// explicitly convert sum to double
// then calculate average
average = (double) sum / n;
printf("Average = %.2lf", average);
return 0;
}
Binary Search
 Binary Search is a searching algorithm for finding an element's position in a sorted array.

 In this approach, the element is always searched in the middle of a portion of an array.

Binary Search Working


Binary Search Algorithm can be implemented in two ways which are discussed below.
1. Iterative Method
2. Recursive Method
The recursive method follows the divide and conquer approach
The general steps for both methods are discussed below.
1. The array in which searching is to be performed is:

Let x = 4 be the element to be searched.

2. Set two pointers low and high at the lowest and the highest positions respectively.

3. Find the middle element mid of the array i.e, arr[(low + high)/2] = 6

4. If x == mid, then return mid.Else, compare the element to be searched with m.

5. If x > mid, compare x with the middle element of the elements on the right side of mid. This is done by
setting low to low = mid + 1.
6. Else, compare x with the middle element of the elements on the left side of mid. This is done by setting
high to high = mid - 1.

7. Repeat steps 3 to 6 until low meets high.

8. x = 4 is found

// Binary Search in C

#include<stdio.h>
#include<string.h>
int main()
{
int a[10],key;
int n,i,low,high,mid,found=0;
printf("enter the number of numbers to read\n");
scanf("%d",&n);
printf("enter the numbers in ascending order\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enter the number to search\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high && !found)
{
mid=(low+high)/2;
if(a[mid]==key)
found=1;
else if(a[mid]<key)
low=mid+1;
else high=mid-1;
}
if(found==1)
printf("\n number found at position:%d",mid+1);
else
printf("\n number not found");
return 0;
}
Established under sub section (3) of Section 1 of Garden City University Act, 2013 (Karnataka Act No. 47 of 2013)

Dr. A P J Abdul Kalam School of Engineering


I Semester, B.Tech in Computer Science and Engineering (AI & ML, CS and DS)
Course Title: Problem Solving Techniques (PST) Course Code: 10ABTEC22114 Year: 2022-2023
Course Delivery Instructor: Ashwini S Date: 27/02/2023 Handout: 30

Bubble Sort

Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until they are in the intended
order.

Just like the movement of air bubbles in the water that rise up to the surface, each element of the array move to the
end in each iteration. Therefore, it is called a bubble sort.

Working of Bubble Sort

1. First Iteration (Compare and Swap)

 Starting from the first index, compare the first and the second elements.
 If the first element is greater than the second element, they are swapped.
 Now, compare the second and the third elements. Swap them if they are not in order.
 The above process goes on until the last element.
2. Remaining Iteration
 The same process goes on for the remaining iterations.
 After each iteration, the largest element among the unsorted elements is placed at the end.

In each iteration, the comparison takes place up to the last unsorted element.
The array is sorted when all the unsorted elements are placed at their correct positions.

// Bubble sort in C

#include<stdio.h> int main()


{
int n,i,j,a[10],temp;
printf("\n enter the number of elements"); scanf("%d",&n);
printf("Enter the array elements\n"); for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++) if(a[j]>a[j+1])
{
temp=a[j]; a[j]=a[j+1]; a[j+1]=temp;
}
}
printf("\nThe sorted elements are\n"); for(i=0;i<n;i++)
printf("%d\n",a[i]); return 0;
}

Output

Enter the number of elements 5


Enter the array elements
23 4 6 12 40
The sorted elements are
4 6 12 23 40
Established under sub section (3) of Section 1 of Garden City University Act, 2013 (Karnataka Act No. 47 of 2013)

Dr. A P J Abdul Kalam School of Engineering


I Semester, B.Tech in Computer Science and Engineering (AI & ML, CS and DS)
Course Title: Problem Solving Techniques (PST) Course Code: 10ABTEC22114 Year: 2022-2023
Course Delivery Instructor: Ashwini S Date: 28/02/2023 Handout: 31

Types of Arrays

Array in C are of two types; Single dimensional arrays(1D) and Multidimensional arrays (2D).

Multi-dimensional Arrays: The most common type of multi-dimensional array that is used in the C language is a 2-
D array. However, the number of dimensions can be more than 2 depending upon the compiler of the user’s system.
These arrays consist of elements that are array themselves.

In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays.
For example,

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. we can think the array as a table with 3 rows
and each row has 4 columns.
Initialization of a 3d array

One can initialize a three-dimensional array in a similar way to a two-dimensional array. Here's an example,

// C program to find the sum of two matrices of order 2*2

#include <stdio.h>
int main()
{
float a[2][2], b[2][2], result[2][2];

// Taking input using nested for loop


printf("Enter elements of 1st matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter a%d%d: ", i + 1, j + 1);
scanf("%f", &a[i][j]);
}

// Taking input using nested for loop


printf("Enter elements of 2nd matrix\n");
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
printf("Enter b%d%d: ", i + 1, j + 1);
scanf("%f", &b[i][j]);
}
// adding corresponding elements of two arrays
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 2; ++j)
{
result[i][j] = a[i][j] + b[i][j];
}

// Displaying the sum


printf("\nSum Of Matrix:");

for (int i = 0; i < 2; ++i)


for (int j = 0; j < 2; ++j)
{
printf("%.1f\t", result[i][j]);

if (j == 1)
printf("\n");
}
return 0;
}

Output:

Example 3: Three-dimensional array

// C Program to store and print 12 values entered by the user

#include <stdio.h>
int main()
{
int test[2][3][2];

printf("Enter 12 values: \n");

for (int i = 0; i < 2; ++i)


{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &test[i][j][k]);
}
}
}

// Printing values with the proper index.

printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
}
}
}

return 0;
}

Output
Established under sub section (3) of Section 1 of Garden City University Act, 2013 (Karnataka Act No. 47 of 2013)

Dr. A P J Abdul Kalam School of Engineering


I Semester, B.Tech in Computer Science and Engineering (AI & ML, CS and DS)
Course Title: Problem Solving Techniques (PST) Course Code: 10ABTEC22114 Year: 2022-2023
Course Delivery Instructor: Ashwini S Date: 01/03/2023 Handout: 32

C Program to Find Transpose of a Matrix

The transpose of a matrix is a new matrix that is obtained by exchanging the rows and columns.

In this program, the user is asked to enter the number of rows r and columns c. Their values should be less than 10 in
this program.

Then, the user is asked to enter the elements of the matrix (of order r*c).

//C Program to find transpose of a matrix

#include <stdio.h>
int main()
{
int a[10][10], transpose[10][10], r, c,i,j;
printf("Enter rows and columns: ");
scanf("%d %d",&r,&c);

// asssigning elements to the matrix

printf("\nEnter matrix elements:\n");


for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
scanf("%d",&a[i][j]);
}
}

for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
transpose[i][j]=a[j][i];
}
}
// printing the transpose

printf("\nTranspose of the matrix:\n");


for(i=0;i<c;i++)
{
for(j=0;j<r;j++)
{
printf("%d \t", transpose[i][j]);
}
printf("\n");
}
return 0;
}

Advantages of Array in C
Arrays have a great significance in the C language. They provide several advantages to the programmers while
programming. Some of them are:

1. Arrays make the code more optimized and clean since we can store multiple elements in a single array at once,
so we do not have to write or initialize them multiple times.
2. Every element can be traversed in an array using a single loop.
3. Arrays make sorting much easier. Elements can be sorted by writing a few lines of code.
4. Any array element can be accessed in any order either from the front or rear in O(1) time.
5. Insertion or deletion of the elements can be done in linear complexity in an array.
Disadvantages of Array in C
Every advantageous thing comes with some disadvantages as well. This stands true for arrays as well. Below are
some of the disadvantages of the array in C:
1. Accessing an array out of bounds: The first disadvantage of arrays is that they are statically allocated. This
means that once their size is initialized, it can not be increased or decreased.
2. Homogeneity: We can store only a single type of element in the array i.e., arrays are homogeneous. We can
not use it as a template. For example, if the array data type is char, then only characters can be stored in the
array. If you try to store integers or any other element of a different data type, it will throw an error.
Established under sub section (3) of Section 1 of Garden City University Act, 2013 (Karnataka Act No. 47 of 2013)

Dr. A P J Abdul Kalam School of Engineering


I Semester, B.Tech in Computer Science and Engineering (AI & ML, CS and DS)
Course Title: Problem Solving Techniques (PST) Course Code: 10ABTEC22114 Year: 2022-2023
Course Delivery Instructor: Ashwini S Date: 02/03/2023 Handout: 33

Pointers in C

A pointer is a variable pointing to the address of another variable. It is declared along with an asterisk symbol (*). The
syntax to declare a pointer is as follows:
datatype *var1

The syntax to assign the address of a variable to a pointer is:


datatype var1, *var2;
var2=&var1;

Different Types of Pointers


There are majorly four types of pointers, they are:
1. Null Pointer
2. Void Pointer
3. Wild Pointer
4. Dangling Pointer

1. Null Pointer:

If you assign a NULL value to a pointer during its declaration, it is called Null Pointer.
Syntax:
Int *var = NULL;
Example:
#include<stdio.h>
int main()
{
int *var = NULL;
printf(“var=%d”,*var);
}

2. Void Pointer:

When a pointer is declared with a void keyword, then it is called a void pointer. To print the value of this pointer, you
need to typecast it.
Syntax:
void *var;

Example:
#include<stdio.h>
int main()
{
int a=2;
void *ptr;
ptr= &a;
printf("After Typecasting, a = %d", *(int *)ptr);
return 0;
}
3. Wild Pointer:

A wild pointer is only declared but not assigned an address of any variable. They are very tricky, and they may cause
segmentation errors.

Example:

#include<stdio.h>
int main()
{
int *ptr;
printf(“ptr=%d”,*ptr);
return 0;
}

4. Dangling Pointer

 Suppose there is a pointer p pointing at a variable at memory 1004. If you deallocate this memory, then this p
is called a dangling pointer.
 You can deallocate a memory using a free() function.
Example:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr=(int *)malloc(sizeof(int));
int a=5;
ptr=&a;
free(ptr);
//now this ptr is known as dangling pointer.
printf(“After deallocating its memory *ptr=%d”,*ptr);
return 0;
}

What Are the Use Cases of Pointers in C?


1. Pointer arithmetic
2. Pointer to pointer
3. Array of pointers
4. Call by value
5. Call by reference

1. Pointer arithmetic:
Increment: You can use this operator to jump from one index to the next index in an array.
Syntax:
ptr++;

Example:
#include <stdio.h>
int main()
{
int arr[3] = {50, 150, 200};
int *ptr;
ptr = arr;
for (int i = 0; i < 3; i++)
{
printf(“Value of *ptr = %d\n”,*ptr);

printf(“Address of *ptr = %d\n”,ptr);

ptr++;
}
Output:

Decrement: You can use this operator to jump from one index to the previous index in an array.
Syntax:
Ptr--;

Example:
#include<stdio.h>
int main()
{
int arr[3]={50, 150, 200};
int *ptr;
ptr = &arr[2];
for (int i=0;i<3;i++)
{
printf("Value of *ptr = %d\n", *ptr);
printf("Address of *ptr = %d\n\n", ptr);
ptr--;
}
}
Output:
2. Pointer to Pointer:

In this situation, a pointer will indirectly point to a variable via another pointer.

Syntax:

Int **ptr;

Example:

#include <stdio.h>

int main ()

int var, *ptr1, **ptr2;

var = 10;

ptr1 = &var;

ptr2 = &ptr1;

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

printf("Value available at *ptr1 = %d\n", *ptr1 );

printf("Value available at **ptr2 =%d\n", **ptr2);

return 0;

Output:
3. An Array of Pointer:

An array of the pointer is an array whose every element is a pointer.

Syntax:

int *arr[n] //where n is size of array.

Example:
#include <stdio.h>
int main ()
{
int a[3] = {10, 100, 200},n=3;
int i, *ptr[3];
for ( i = 0; i < 3; i++)
{
ptr[i] = &a[i];
}
for ( i = 0; i < n; i++)
{
printf("Value of a[%d] = %d\n", i, *ptr[i] );
}
return 0;
}

Output:
Established under sub section (3) of Section 1 of Garden City University Act, 2013 (Karnataka Act No. 47 of 2013)

Dr. A P J Abdul Kalam School of Engineering


I Semester, B.Tech in Computer Science and Engineering (AI & ML, CS and DS)
Course Title: Problem Solving Techniques (PST) Course Code: 10ABTEC22114 Year: 2022-2023
Course Delivery Instructor: Ashwini S Date: 13/03/23 Handout: 34

Relationship Between Arrays and Pointers


An array is a block of sequential data. Let's write a program to print addresses of array elements.

There is a difference of 4 bytes between two consecutive elements of array x. It is because the size of int is 4 bytes (on
our compiler).

Notice that, the address of &x[0] and x is the same. It's because the variable name x points to the first element of the
array.
From the above example, it is clear that &x[0] is equivalent to x. And, x[0] is equivalent to *x.
Similarly,
&x[1] is equivalent to x+1 and x[1] is equivalent to *(x+1).
&x[2] is equivalent to x+2 and x[2] is equivalent to *(x+2).
...
Basically, &x[i] is equivalent to x+i and x[i] is equivalent to *(x+i).

Example 1: Pointers and Arrays

Here, we have declared an array x of 6 elements. To access elements of the array, we have used pointers.
In most contexts, array names decay to pointers. In simple words, array names are converted to pointers. That's the
reason why you can use pointers to access elements of arrays. However, you should remember that pointers and
arrays are not the same.
Example 2: Arrays and Pointers

In this example, &x[2], the address of the third element, is assigned to the ptr pointer. Hence, 3 was displayed when
we printed *ptr.

And, THERE ARE SEVERAL DIFFERENT USES OF POINTERS IN C...THEY ARE


(1) int *p;
// p is a pointer to an integer quantity
(2) int *p[10];
// p is a 10-element array of pointers to integer quantities
(3) int (*p)[10];
// p is a pointer to a 10-element integer array
(4) int *p(void);
// p is a function that returns a pointer to an integer quantity
(5) int p(char *a);
// p is a function that accepts an argument which is a pointer to a character returns an integer quantity
(6) int *p(char *a);
// p is a function that accepts an argument which is a pointer to a character returns a pointer to an integer quantity.
(7) int (*p)(char *a);
// p is pointer to a function that accepts an argument which is a pointer to a character returns an integer quantity.
(8) int (*p(char *a))[10];
// p is a function that accepts an argument which is a pointer to a character returns a pointer to a 10-element integer array.
(9) int p(char (*a)[]);
// p is a function that accepts an argument which is a pointer to a character array returns an integer quantity.
(10) int p(char *a[]);
// p is a function that accepts an argument which is a array of pointers to characters returns an integer quantity
(11) int *p(char a[]);
// p is a function that accepts an argument which is a character array returns a pointer to an integer quantity
(12) int *p(char (*a)[]);
// p is a function that accepts an argument which is a pointer to a character array returns a pointer to an integer quantity
(13) int *p(char *a[]);
// p is a function that accepts an argument which is an array of pointers to characters
// returns a pointer to an integer quantity
(14) int (*p)(char (*a)[]);
// p is pointer to a function that accepts an argument which is a pointer to a character array returns an integer quantity
(15) int *(*p)(char (*a)[]);
// p is pointer to a function that accepts an argument which is a pointer to a character array returns a pointer to an integer
quantity
(16) int *(*p)(char *a[]);
// p is pointer to a function that accepts an argument which is a array of pointers to characters returns a pointer to an
integer quantity
(17) int (*p[10])(void);
// p is 10-element array of pointers to functions; each function returns an integer quantity
(18) int (*p[10])(char a);
// p is 10-element array of pointers to functions; each function accepts an argument which is a character and returns an
integer quantity
(19) int *(*p[10])(char a);
// p is 10-element array of pointers to functions; each function accepts an argument which is a character and returns a
pointer to an integer quantity
(20) int *(*p[10])(char *a);
// p is 10-element array of pointers to functions; each function accepts an argument which is a pointer to a character and
returns a pointer to an integerprinting *(ptr+1) gives us the fourth element. Similarly, printing *(ptr-1) gives us the
second element.
Established under sub section (3) of Section 1 of Garden City University Act, 2013 (Karnataka Act No. 47 of 2013)

Dr. A P J Abdul Kalam School of Engineering


I Semester, B.Tech in Computer Science and Engineering (AI & ML, CS and DS)
Course Title: Problem Solving Techniques (PST) Course Code: 10ABTEC22114 Year: 2022-2023
Course Delivery Instructor: Ashwini S Date: 13/03/23 Handout: 35

C Pass Addresses and Pointers


In C programming, it is also possible to pass addresses as arguments to functions.
To accept these addresses in the function definition, we can use pointers. It's because pointers are used to store
addresses. Let's take an example:

Example: Pass Addresses to Functions


The address of num1 and num2 are passed to the swap() function using swap(&num1, &num2);.
Pointers n1 and n2 accept these arguments in the function definition

When *n1 and *n2 are changed inside the swap() function, num1 and num2 inside the main() function are also
changed.
Inside the swap() function, *n1 and *n2 swapped. Hence, num1 and num2 are also swapped.
Notice that swap() is not returning anything; its return type is void.

Example 2: Passing Pointers to Functions

Here, the value stored at p, *p, is 10 initially.


We then passed the pointer p to the addOne() function. The ptr pointer gets this address in the addOne() function.
Inside the function, we increased the value stored at ptr by 1 using (*ptr)++;. Since ptr and p pointers both have the
same address, *p inside main() is also 11.
Established under sub section (3) of Section 1 of Garden City University Act, 2013 (Karnataka Act No. 47 of 2013)

Dr. A P J Abdul Kalam School of Engineering


I Semester, B.Tech in Computer Science and Engineering (AI & ML, CS and DS)
Course Title: Problem Solving Techniques (PST) Course Code: 10ABTEC22114 Year: 2022-2023
Course Delivery Instructor: Ashwini S Date: 15/03/2023 Handout: 36

C Dynamic Memory Allocation


As you know, an array is a collection of a fixed number of values. Once the size of an array is declared, you cannot
change it.

Sometimes the size of the array you declared may be insufficient. To solve this issue, you can allocate memory
manually during run-time. This is known as dynamic memory allocation in C programming.

To allocate memory dynamically, library functions are malloc(), calloc(), realloc() and free() are used. These
functions are defined in the <stdlib.h> header file.

C malloc()
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes. And, it returns a pointer of void
which can be casted into pointers of any form.

Syntax of malloc()

Example

The above statement allocates 400 bytes of memory. It's because the size of float is 4 bytes. And, the pointer ptr holds
the address of the first byte in the allocated memory.
The expression results in a NULL pointer if the memory cannot be allocated.
C calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory uninitialized, whereas the calloc() function allocates
memory and initializes all bits to zero.
Syntax of calloc()

Example:

The above statement allocates contiguous space in memory for 25 elements of type float.

C free()
Dynamically allocated memory created with either calloc() or malloc() doesn't get freed on their own. You must
explicitly use free() to release the space.
Syntax of free()

This statement frees the space allocated in the memory pointed by ptr.

Example 1: malloc() and free()


// Program to calculate the sum of n numbers entered by the user
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);
ptr = (int*) malloc(n * sizeof(int));
// if memory cannot be allocated
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}

Output:

Here, we have dynamically allocated the memory for n number of int.

Example 2: calloc() and free()

// Program to calculate the sum of n numbers entered by the user

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

int main() {
int n, i, *ptr, sum = 0;
printf("Enter number of elements: ");
scanf("%d", &n);

ptr = (int*) calloc(n, sizeof(int));


if(ptr == NULL) {
printf("Error! memory not allocated.");
exit(0);
}

printf("Enter elements: ");


for(i = 0; i < n; ++i) {
scanf("%d", ptr + i);
sum += *(ptr + i);
}

printf("Sum = %d", sum);


free(ptr);
return 0;
}

Output:

C realloc()
If the dynamically allocated memory is insufficient or more than required, you can change the size of previously
allocated memory using the realloc() function.
Syntax of realloc()

Here, ptr is reallocated with a new size x.

Example 3: realloc()
#include <stdio.h>
#include <stdlib.h>

int main()
{
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);

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

printf("Addresses of previously allocated memory:\n");


for(i = 0; i < n1; ++i)
printf("%pc\n",ptr + i);

printf("\nEnter the new size: ");


scanf("%d", &n2);

// rellocating the memory


ptr = realloc(ptr, n2 * sizeof(int));

printf("Addresses of newly allocated memory:\n");


for(i = 0; i < n2; ++i)
printf("%pc\n", ptr + i);

free(ptr);

return 0;
}

Output:

You might also like