You are on page 1of 82

LECTURE NOTES

ON

COMPUTER PROGRAMMING

I B.TECH I SEMESTER
Regulation: R20

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


SRINIVASA RAMANUJAN INSTITUTE OF TECHNOLOGY
(Affiliated to JNTUA & Approved by AICTE)
Rotarypuram Village, B K Samudram Mandal, Ananthapuramu - 515701.

(2020 – 2021)
Problem Solving & Programming

UNIT – IV

Arrays, Strings and Pointers

Introduction, One-dimensional arrays, strings: one-dimensional character arrays,


multi-dimensional arrays, array of strings.
Introduction, understanding memory addresses, address operator, pointer, void
pointer, null pointer, use of pointers, arrays and pointers, pointers and strings. Pointers to
pointers. Pointers to functions, dynamic memory allocation.

Learning Outcomes:
At the end of unit, students will be able to
1. Apply String manipulation functions.
2. Structure the individual date elements to simplify the solutions.
3. Organize homogenous data.
4. Facilitate efficient memory utilization.

ARRAYS
Introduction:
Arrays a kind of data structure that can store a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type, hence an array is also
defined as homogeneous collection of elements.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers. A specific element in an array is
accessed by an index or subscript. An array index starts from 0(zero) by default.
All array elements consist of contiguous memory locations. The lowest address
corresponds to the first element and the highest address to the last element.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 2


Problem Solving & Programming

Types of Arrays:
Arrays are classified into two types based on their subscripts.
1. One-Dimensional Arrays
2. Multi-Dimensional Arrays

One- Dimensional Arrays:

A one-dimensional array is like a list, a set.

Ex:
25

32

45 25 32 45 56 87 95 67
56
Horizantal List of 7 elements
87

95

67

Vertical List of 7 elements

Since the elements of an array are arranged in only one dimension i.e; towards either x-
dimension or y-dimension, hence they are called as one-dimensional arrays.

How an ordinary variable is different from an array?

The fundamental data types like int, float and char have a fact that a variable of these types
can store or hold only one value at any given time. Hence to use another value we need to
declare another new variable. It means for n values we need to declare ‘n’ different variables.
For example, to store marks of 6 subjects, it is required to declare 6 different variables as
follows:
int t, h, e, m, sc, so;
So, if we need to store a large volume of data in terms of reading, processing and printing, it is
not possible with an ordinary variable. Hence C supports a powerful data type called Array. It
is used to store more than one data value under a single name.
For example, to store marks of 6 subjects, declare an integer array called marks of size 6 as
follows:
int marks[6];

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 3


Problem Solving & Programming

Declaration of an Array:

To declare an array in C, a programmer specifies the type of the elements and the number of
elements required by an array as follows –

Syntax:

data type array_name [ array_size ];

This is called a single-dimensional array. The array_size must be an integer constant greater
than zero and type can be any valid C data type.

Example:

To declare a 10-element array called price of type float, use this statement

float price[10];

Here price is a variable array which is sufficient to hold up to 10 prices.

To declare a 6-element array called marks of type int, use this statement

int marks[6];

Here marks is a variable array which is sufficient to hold up to 6 subjects marks.


Initialization of an Array:
We can initialize an array in C either one by one or using a single statement.
Syntax:
array_name[size] = { value1, value2, .................................................. };
OR
array_name[ ] = { value1, value2, ............................................. };

Example:
Assume an array that stores marks of 6 subjects.
We can initialize an array in C either one by one or using a single statement.

Ex:
marks[0] = 75;

marks[1] = 95;

marks[2] = 85;
OR marks[6] = {75, 95, 85, 68, 74, 46};
marks[3] = 68;

marks[4] = 74;

marks[5] = 46;
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 4
Problem Solving & Programming

The number of values between braces { } cannot be larger than the size of an array.

If you omit the size of the array, an array just big enough to hold the initialization is created.
Therefore, if you write −

int marks[ ] = {75, 95, 85, 68, 74, 46};

will creates exactly the same array as you did in the previous example.

Example: Declaration and Initialization of an Array

int ages[10];

ages[6] = {25, 15, 20, 36, 45, 54};

OR

int ages[6] = {25, 15, 20, 36, 45, 54};

OR

int ages[ ] = {25, 15, 20, 36, 45, 54};

Accessing Elements of an Array:


An element in array is accessed by its index and array_name. This is done by placing the index
of the element within square brackets after the name of the array.
For example
int age1 = ages[3];
The above statement will take the 4th element from the array ages and assign the value to a
variable age1. Therefore, the value of age1 is 36.

Reading elements to an array using scanf( ):

To read elements to an array, looping statement is used to change the index of the element,
since all the elements will differ by its index only.
Ex:
int ages[10], in;
for(in=0; in<10; in++)
{
scanf(“%d”, &ages[in]);
}

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 5


Problem Solving & Programming

Printing or Displaying the elements of an array using printf( ):

To print or display elements of an array, looping statement is used to change the index of the
element, since all the elements will differ by its index only.
The way we use to read the elements to an array is similar to that of printing an array.
Ex:
int ages[10], in;
for(in=0; in<10; in++)
{
printf(“%d \t”, ages[in]);
}

Finding the address of the required element of an array:


All elements of an array will store in contiguous memory locations. We can find out the
address of any desired element of an array using the address of the first element called Base
Address and the index of the desired element as follows:

Address of the desired element =


(Address of the first element + (index of the desired element *
scale_factor))
Here, scale_factor denotes the size of the corresponding data type.
Consider the following array having its elements and their address.
int arr[6] = {25, 37, 48, 85, 56, 98};

arr[index] arr[0] arr[1] arr[2] arr[3] arr[4] arr[5]

Element 25 37 48 85 56 98

Address 25681 25683 25685 25687 25689 25691

Suppose to find the address of 5th element and its index is 4.


Here,
Address of the first element: 25681
Address of the nth element =
Address of the first element + index of the desired element * scale_factor
Address of the 5th element
= Address of the first element + index of the 5th element * sizeof(int)
= 25681 + (4 * 2)
= 25681 + 8 = 25689

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 6


Problem Solving & Programming

Program:
Write a C program to illustrate the declaration and initialization of an array.
Source Code:
#include<stdio.h>
void main( )
{
int arr[6], i;
printf(“Enter array elements one by one:”);
for(i=0; i<6; i++)
{
scanf(“%d”, &arr[i]);
}
printf(“\n The array elements are:\n”);
for(i=0;i<6;i++)
{
printf(“arr[%d] = %d \n”, i, arr[i]);
}

Output:
Enter array elements one by one: 26
38
49
87
96
256
The array elements are:
arr[0] = 26
arr[1] = 38
arr[2] = 49
arr[3] = 87
arr[4] = 96
arr[5] = 256

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 7


Problem Solving & Programming

Program:
Write a C program to find the sum of all array elements.
Source Code:
/* C Program to find sum of all array elements */
#include <stdio.h>
#define MAX 100
void main( )
{
int arr[MAX], N, i, sum = 0;
printf("Enter Number of Elements in Array:");
scanf("%d", &N);
printf("Enter %d numbers one by one:", N);
for(i = 0; i < N; i++) /* Read array elements */
{
scanf("%d", &arr[i]);
}
for(i = 0; i < N; i++) /* Add array elements */
{
sum = sum + arr[i];
}
printf("Sum of all Array Elements : %d", sum);
}

Output:
Enter Number of Elements in Array: 5
Enter 5 numbers one by one: 25
15
10
98
64
Sum of all Array Elements: 212
Program:
Write a C program to find the maximum and minimum element of an array.
Source Code:
#include <stdio.h>
#define SIZE 100
void main( )
{
int arr[SIZE], N, max, min, i;
printf("Enter Number of Elements in Array:");

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 8


Problem Solving & Programming

scanf("%d", &N);
printf("Enter %d numbers one by one:", N);
for(i = 0; i < N; i++) /* Read array elements */
{
scanf("%d", &arr[i]);
}
max = min = arr[0];
for(i = 1; i < N; i++) /* find max and min of an array */
{
if(arr[i] > max)
max = arr[i];
if(arr[i] < max)
min = arr[i];
}
printf("Maximum element of an array : %d", max);
printf("Minimum element of an array : %d", min);
}

Output:
Enter Number of Elements in Array: 5
Enter 5 numbers one by one: 156
24
31
12
10
Maximum element of an array: 156
Minimum element of an array: 10

Program:
Write a C program to reverse an array.
Source Code:
#include <stdio.h>
#define SIZE 100
void main( )
{
int arr[SIZE], N, i;
printf("Enter Number of Elements in Array:");
scanf("%d", &N);
printf("Enter %d numbers one by one:", N);
for(i = 0; i < N; i++) /* Read array elements */
{

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 9


Problem Solving & Programming

scanf("%d", &arr[i]);
}
printf("\n Array Elements are: \n");
for(i = 0; i < N; i++)
{
printf("%d \t", arr[i]);
}
printf("\n Reverse of an array: \n");
for(i=N-1; i>=0; i--)
{
printf("%d \t", arr[i]);
}
}
Output:
Enter Number of Elements in Array: 5
Enter 5 numbers one by one: 36
92
45
67
89
Array Elements are:
36 92 45 67 89
Reverse of an array:
89 67 45 92 36

Program:
Write a C program to sort an array in ascending order (increasing order).
Source Code:
#include<stdio.h>
#define MAX 100
void main()
{
int arr[MAX],i,j,n,temp;
printf("\n Enter no.of elements in array:");
scanf("%d",&n);

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 10


Problem Solving & Programming

printf("\n Enter %d elements one by one:",n);


for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\n Array before sorting:\n");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n; j++)
{
if(arr[j]<arr[i])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("\n Array after sorting:\n");
for(i=0;i<n;i++)
{
printf("%d\t",arr[i]);
}
}

Output:

Enter no.of elements in array: 5


Enter 5 elements one by one: 98
76
85
62
13

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 11


Problem Solving & Programming

Array before sorting:


98 76 85 62 13
Array after sorting:
13 62 76 85 98

Multi-dimensional arrays:
An array with more than one-dimension is called a multi-dimensional array. Hence the
two dimensional, three dimensional or other dimensional arrays are also known as multi-
dimensional arrays.
The simplest form of the multidimensional array is the two-dimensional array. A two-
dimensional array is defined as an array of one-dimensional arrays. A 2D-array is used to
organize the elements in a tabular form or matrix form. A 2D-array is best suitable for
manipulating matrices, since a matrix is defined as a collection of numbers arranged into a
fixed number of rows and columns.
General Form
Declaration of Two-dimensional arrays:
Syntax:
data type array_name [row_size ][col_size];
This is called a two-dimensional array. The row_size, col_size must be an integer constant
greater than zero and data type can be any valid C data type.
Example:
int a[3][4];
It is a two-dimensional integer array having maximum 3 rows and 4 columns.

Initialization of Two-dimensional arrays:


Syntax: A two-dimensional is initialized in many forms as follows:
array_name[row_size][col_size] = { {e1,e2,e3, .........}, {e4,e5,e6, .........}, ............. };
OR
array_name[row_size][col_size] = {
{e1,e2,e3, .............},

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 12


Problem Solving & Programming

{e4,e5,e6, .............}, .................


};
OR
A two dimensional array arr[n1][n2] can have n1*n2 elements.
array_name[row_size][col_size] = {e1,e2,e3,e4,e5,e6, ......................};
Example:
a[3][4] = { {21,72,93,54}, {81,52,61,34}, {41,32,22,94} };
OR
a[3][4] = { 21,72,93,54,81,52,61,34,41,32,22,94 };
OR
a[3][4] = {
{21,72,93,54},
{81,52,61,34},
{41,32,22,94}
};

COLUMN 0 COLUMN 1 COLUMN 2 COLUMN 3


ROW 0 21 72 93 54
a[0][0] a[0][1] a[0][2] a[0][3]
ROW 1 81 52 61 34
a[1][0] a[1][1] a[1][2] a[1][3]
ROW 2 41 32 22 94
a[2][0] a[2][1] a[2][2] a[2][3]

Things that you must consider while initializing a 2D array


We already know, when we initialize a one dimensional array during declaration, we
need not to specify the size of it. However that’s not the case with 2D array, you must always
specify the second dimension even if you are specifying elements during the declaration.
Let’s understand this with the help of few examples –
int abc[2][2] = {1, 2, 3 ,4 }; /* Valid declaration*/
int abc[ ][2] = {1, 2, 3 ,4 }; /* Valid declaration*/
int abc[ ][ ] = {1, 2, 3 ,4 }; /* Invalid declaration – you must specify second dimension*/
int abc[2][ ] = {1, 2, 3 ,4 }; /* Invalid declaration – you must specify second dimension */

Size of multidimensional arrays


Total number of elements that can be stored in a multidimensional array can be
calculated by multiplying the size of all the dimensions.
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 13
Problem Solving & Programming

For example:
The array int a[10][20] can store (10*20) = 200 elements.
Similarly array int a[5][10][20] can store (5*10*20) = 1000 elements.

Accessing Elements of Two-Dimensional Arrays:


Elements in Two-Dimensional arrays are accessed using the row indexes and column
indexes. By default the row_index and column_index starts from 0.
Example:
int arr[3][4];
int m = arr[2][1];
The above example represents the element present in third row and second column.
Note: In 1D arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row_index
2 row number is 2+1 = 3 and for col_index 1 column number is 2.
Storage of elements in 2D – array:
All the elements of a 2D-array are logically represented as tabular form or matrix form
but physically in memory they will store in contiguous memory locations.

Logical representation of a two-dimensional array

a[0][0]

a[0][1]

a[0][2]

a[0][3]

a[1][0]

a[1][1]

a[1][2]

a[1][3]

a[2][0]

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 14


Problem Solving & Programming

a[2][1]

a[2][2]

a[2][3]

Physical storage of a two-dimensional array in memory

Reading elements to a 2D-array using scanf( ):


To read elements to a 2D-array, nested looping statement is used to change the row_index and
column_index of the element, since all the elements will differ by its row and column index
only.
Ex:
int matA[5][5], ri, ci;
for(ri=0; ri<5; ri++)
{
for(ci=0;ci<5;ci++)
{
scanf(“%d”, &matA[ri][ci]);
}
}
Printing or Displaying the elements of a 2D-array using printf( ):

To print or display elements of a 2D-array, nested looping statement is used to change the
row_index and column_index of the element, since all the elements will differ by its row and
column index only.
The way we use to read the elements to an array is similar to that of printing an array.
Ex:
int matA[5][5], ri, ci;
for(ri=0; ri<5; ri++)
{
for(ci=0;ci<5;ci++)
{
printf(“%d\t”, matA[ri][ci]);
}
printf(“\n”);
}

Finding the address of the required element inTwo-Dimensional Array:


While storing the elements of a 2-D array in memory, these are allocated contiguous memory
locations. Therefore, a 2-D array must be linearized so as to enable their storage.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 15


Problem Solving & Programming

There are two alternatives to achieve linearization:


Row-Major and Column-Major.

Address of an element of any array say “A[I][J]” is calculated in two forms as given:
(1) Row Major System (2) Column Major System
Row Major System:
The address of a location in Row Major System is calculated using the following formula:
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
Column Major System:
The address of a location in Column Major System is calculated using the following formula:
Address of A [ I ][ J ] = B + W * [( I – Lr ) + M * ( J – Lc )]
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 16
Problem Solving & Programming

Where,
B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
M = Number of row of the given matrix
N = Number of column of the given matrix

Example:
Consider a two-dimensional array: int a[3][4];
Address Element Reference

25001 25 a[0][0]

25003 36 a[0][1]

25005 84 a[0][2]

25007 56 a[0][3]

25009 15 a[1][0]

25011 12 a[1][1]

25013 14 a[1][2]

25015 17 a[1][3]

25017 83 a[2][0]

25019 62 a[2][1]

25021 97 a[2][2]

25023 95 a[2][3]

Find the address of the element a[2][1]


Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
Address of A [ 2 ][ 1 ] = 25001 + 2*(4 * (2-0) + (1-0))
= 25001 + 2*(4*2+1)
=25001 + 2*9
=25001 + 18 = 25019
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 17
Problem Solving & Programming

Program:
Write a C program to read and display a matrix of any order.
Source Code:
#include<stdio.h>
#define ROWS 10
#define COLS 10
void main( )
{
int mat[ROWS][COLS];
int i,j,r1,c1;
printf("Enter no. of rows and columns in a matrix:");
scanf("%d%d",&r1,&c1);
printf("\n Enter %d elements one by one:",r1*c1);
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d", &mat[i][j]);
}
}
printf("\n Matrix is:\n\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%d\t", mat[i][j]);
}
printf("\n\n");
}
}

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 18


Problem Solving & Programming

Output:
Enter no. of rows and columns in a matrix: 3 3
Enter 9 elements one by one: 16
25
34
85
97
54
62
13
15
Matrix is:
16 25 34

85 97 54

62 13 15

Program:
Write a C program to read two matrices and then find the sum of two matrices.
Source Code:
#include<stdio.h>
#define ROWS 10
#define COLS 10
void main()
{
int a[ROWS][COLS], b[ROWS][COLS], c[ROWS][COLS];
int i,j,r1,c1,r2, c2;
printf("Enter no. of rows and columns in matrix A:");
scanf("%d%d",&r1,&c1);
printf("Enter no. of rows and columns in matrix B:");
scanf("%d%d",&r2,&c2);
if((r1==r2)&&(c1==c2))
{
printf("Enter elements of matrix A:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 19


Problem Solving & Programming

{
scanf("%d", &a[i][j]);
}
}
printf("Enter elements of matrix B:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d", &b[i][j]);
}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf("Matrix A is:\n\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%d\t", a[i][j]);
}
printf("\n\n");
}
printf("\n Matrix B is:\n\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t", b[i][j]);
}
printf("\n\n");
}

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 20


Problem Solving & Programming

printf("\n Sum Matrix C is:\n\n");


for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%d\t", c[i][j]);
}
printf("\n\n");
}
}
else
{
printf("\n Oops! Matrix addition is not possible.\n");
}
}

Output-1:

Enter no. of rows and columns in matrix A: 2 3

Enter no. of rows and columns in matrix B: 2 3

Enter elements of matrix A: 12 15 13 10 11 16

Enter elements of matrix B: 10 4 5 16 17 14

Matrix A is:

12 15 13

10 11 16

Matrix B is:

10 4 5

16 17 14

Sum Matrix C is:

22 19 18

26 28 30

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 21


Problem Solving & Programming

Output-2:

Enter no. of rows and columns in matrix A: 5 3

Enter no. of rows and columns in matrix B: 2 4

Oops! Matrix addition is not possible.


Program:

Write a C program to read two matrices and then find the product of two matrices.

Source Code:

#include<stdio.h>
#define ROWS 10
#define COLS 10
void main()
{
int a[ROWS][COLS],b[ROWS][COLS],c[ROWS][COLS];
int i,j,k,r1,c1,r2,c2;
printf("Enter no.of rows and columns in matrix A:");
scanf("%d%d",&r1,&c1);
printf("Enter no.of rows and columns in matrix B:");
scanf("%d%d",&r2,&c2);
if(c1==r2) /* no. of columns in matrix A and no. of rows in matrix B must be equal */
{
printf("Enter elements of matrix A:");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("Enter elements of matrix B:");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
scanf("%d",&b[i][j]);

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 22


Problem Solving & Programming

}
}
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
c[i][j]=0;
for(k=0;k<c1;k++)
{
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
}
printf("Matrix A is:\n\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
{
printf("%d\t",a[i][j]);
}
printf("\n\n");
}
printf("\n Matrix B is:\n\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t",b[i][j]);
}
printf("\n\n");
}
printf("\n Product Matrix C is:\n\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t",c[i][j]);

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 23


Problem Solving & Programming

}
printf("\n\n");
}
}
else
{
printf("\n Oops! Matrix Multiplication is not possible.\n");
}
}

Output-1:

Enter no.of rows and columns in matrix A: 2 3

Enter no.of rows and columns in matrix B: 3 2

Enter elements of matrix A: 1 1 1 1 1 1

Enter elements of matrix B: 1 1 1 1 1 1

Matrix A is:

1 1 1

1 1 1

Matrix B is:

1 1

1 1

1 1

Product Matrix C is:

3 3

3 3

Output-2:

Enter no. of rows and columns in matrix A: 3 4

Enter no. of rows and columns in matrix B: 3 5

Oops! Matrix Multiplication is not possible.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 24


Problem Solving & Programming

Arrays and Functions


It is possible to pass any type of argument to a function, similarly we can also pass an
array as an argument to a function.

Following are the different ways of passing elements of an array to a function


1. Passing elements of an array as element by element (individual array elements)
2. Passing entire as an argument

1. Passing elements of an array as element by element (individual array elements)


Passing array elements to a function is similar to passing variables to a function.

Program-1:
Program to illustrate how array elements passed as an argument to a function
Source Code:
#include <stdio.h>
void disp( char );
int main( )
{
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'};
for (int x=0; x<10; x++)
{
disp (arr[x]); // passing array elements one by one
}
return 0;
}
void disp( char ch)
{
printf("%c ", ch);
}

Output:
a b c d e f g h i j

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 25


Problem Solving & Programming

Program-2:
Program to update elements of an array using functions such that each element of an array
should be multiplied by 5.

Source Code:

/* Program to update elements of an array using functions */


#include<stdio.h>
#define MAX 50
int main( )
{
int arr[MAX], n, idx;
int update_array(int);
printf("Enter no. of elements:");
scanf("%d", &n);
printf("Enter %d elements:",n);
for(idx=0; idx<n; idx++)
scanf("%d", &arr[idx]);
printf("Before update:\n");
for(idx=0;idx<n; idx++)
printf("%d ", arr[idx]);
//update the elements of the array
for(idx=0;idx<n; idx++)
arr[idx]=update_array(arr[idx]); //passing element by element through index
printf("\nAfter update:\n");
for(idx=0;idx<n; idx++)
printf("%d ", arr[idx]);
}
int update_array(int ele) //ele is the element of an array
{
return ele*5;
}

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 26


Problem Solving & Programming

Output:
Enter no. of elements: 5
Enter 5 elements: 10 20 30 40 50
Before update:
10 20 30 40 50
After update:
50 100 150 200 250

2. Passing an array as an argument to a function

It is also possible to pass an entire array as an argument to a function. In such case we


must know how to declare such functions, how to call such functions and how to define such
functions.
We know that the array_name contains the address of the first element. Here, we must
notice that we need to pass only the name of the array in the function which is intended to
accept an array. The array defined as the formal parameter will automatically refer to the
array specified by the array name defined as an actual argument.

Methods to declare a function that receives an array as an argument

There are 3 ways to declare the function which is intended to receive an array as an argument.
Syntax-1:
return_type function(type arrayname[]);
Declaring blank subscript notation [] is the widely used technique.
Syntax-2:
return_type function(type arrayname[SIZE]);
Optionally, we can define size in subscript notation [].
Syntax-3:
return_type function(type *arrayname);
You can also use the concept of a pointer.

To call any function by passing an entire array as an argument, we need to pass array_name as
argument, since array name itself acts as a pointer, this method of passing mechanism is
called call-by-reference.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 27


Problem Solving & Programming

Syntax:
function_name(array_name);
Example:
read_array(arr);
Program:
Program to find square of each element of an array using functions.
Source Code:
/* Program to pass an entire array as argument to a function */
#include<stdio.h>
#define MAX 50
int main()
{
int arr[MAX],n;
void read_array(int[ ], int);//function declaration
void display_array(int[ ], int);
void squaring(int[ ], int);
printf("Enter no. of elements:");
scanf("%d", &n);
printf("Enter %d elements:",n);
read_array(arr, n);//function call
printf("\n Before squaring:\n");
display_array(arr, n);
squaring(arr, n);//calling squaring function
printf("\n After squaring:\n");
display_array(arr, n);
}
void read_array(int a[ ],int n)
{
int idx;
for(idx=0;idx<n; idx++)
scanf("%d", &a[idx]);
}

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 28


Problem Solving & Programming

void display_array(int a[ ], int n)


{
int idx;
for(idx=0;idx<n; idx++)
printf("%d ", a[idx]);
}
void squaring(int a[ ], int n)
{
int idx;
for(idx=0;idx<n; idx++)
a[idx]=a[idx]*a[idx];
}

Output:
Enter no. of elements: 6
Enter 6 elements: 2 4 6 8 10 12
Before squaring:
2 4 6 8 10 12
After squaring:
4 16 36 64 100 144

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 29


Problem Solving & Programming

Passing a Two-Dimensional Array to a function


A one dimensional array can be easily passed as a pointer, but while passing a 2D array
to a function, one important thing for passing multidimensional arrays is, first dimension is
may or may not be specified. The second (and any subsequent) dimensions must be given.
Function accepting 2D array as an argument can be declared as follows:
Syntax:
return_type function_name(datatype [ ][col_size]);

Program:
Program to find the transpose of a given matrix using functions
Source Code:
/* Program to find transpose of a matrix */
#include<stdio.h>
#define ROW 15
#define COL 15
int main( )
{
void read_matrix(int[ ][COL], int, int); // function declaration
void display_matrix(int[ ][COL], int, int);
void transpose(int[ ][COL], int, int);
int mat[ROW][COL], m, n;
printf("Enter the size of a matrix:");
scanf("%d %d", &m, &n);
printf("Enter %d elements of a matrix:",m*n);
read_matrix(mat, m, n);//function call for reading the elements
printf("Before Transposing:\n");
display_matrix(mat, m, n); // calling display_matrix function
printf("\n After Transposing:\n");
transpose(mat, m, n);//calling transpose function
}
void read_matrix(int a[ ][COL], int m, int n)
{
int i, j;
for(i=0;i<m; i++)

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 30


Problem Solving & Programming

for(j=0;j<n; j++)
scanf("%d", &a[i][j]);
}
void display_matrix(int a[ ][COL], int m, int n)
{
int i, j;
for(i=0;i<m; i++)
{
for(j=0;j<n; j++)
printf("%d ",a[i][j]);
printf("\n");
}
}
void transpose(int a[ ][COL], int m, int n)
{
int i, j;
for(i=0;i<n; i++)
{
for(j=0;j<m; j++)
printf("%d ",a[j][i]);
printf("\n");
}
}
Output:
Enter the size of a matrix: 2 3
Enter 6 elements of a matrix: 12 14 15 21 22 23
Before Transposing:
12 14 15
21 22 23
After Transposing:
12 21
14 22
15 23

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 31


Problem Solving & Programming

Program Assignment:

1. Write a C program to sort the given array in descending order.


2. Write a C program to find the sum of all elements of a floating-point array.
3. Write a C Program to create a duplicate array.
4. Write a C Program to search an element in an array.
5. Write a C Program to find transpose of a given matrix.
6. Write a C Program to find sum of diagonal elements of a matrix.
7. Write a C program to compare two matrices.
8. Write a C Program to sum each row and column of matrix.
9. Write a C program to print sum of even numbers and sum of odd numbers of a matrix.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 32


Problem Solving & Programming

STRINGS
Introduction:

 In C language the group of characters, digits or special characters enclosed in double


quotation marks are called as “Strings”.
 In other words, character arrays are called as strings.
 The string is always declared as character array.
 Every string is terminated with ‘\0’ (Null character).
 The decimal value of Null character is zero (0). It is not compulsory to write ‘\0’ at the
end of the string.
 Each character of the string occupies 1 byte of memory.
 The characters of the string are stored in continuous memory locations.

Declaration and Initialization of Strings:

C does not support strings as a data type, hence strings are always should be declared as
character arrays.

Declaration of character arrays:


Syntax:
char string_name[size];
Here,
char -> data type
string_name -> any valid identifier
size -> Maximum no.of characters present in string
Examples:
char name[15];
char city[15];
char branch[20];
Note: The ‘size’ should be equal to the maximum no. of characters in the string plus one.

Initialization of character arrays:

Syntax-1:
char string_name[size] = “string”;
Example:
char college_name = “SRIT”;
char student_name = “Gautham”;
Syntax-2:
char string_name[size] = {‘ch1’,’ch2’,’ch3’, . . . . . . . . . ,’\0’};

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 33


Problem Solving & Programming

Example:
char student_name = {‘G’,’A’,’U’,’T’,’H’,’A’,’M’,’\0’};

Note: When we initialize a character array as character by character, we must supply the null
character explicitly.

Reading strings from terminal:

1. Using scanf( ) function


scanf( ) uses %s format specifier to read string of characters.
Syntax:
scanf(“%[^\n]s”, string_name);

Here,

[^\n] is used to read multi word strings


In case of character arrays, & is not required before string_name

Example:
char student_name[25];
scanf(“%[^\n]s”, student_name);

2. Using gets( ) function

This is another method called unformatted input function to read a string of text.
Syntax:
gets(string_name);
Example:
gets(student_name);
Displaying strings on the screen:

1. Using printf( ) function

printf( ) uses %s format specifier to display string of characters on the screen.


Syntax:
printf(“%s”, string_name);
Example:
printf(“%s”,student_name);
2. Using puts( ) function
This is another method called unformatted output function to read a string of text.
Syntax:
puts(string_name);
Example:
puts(student_name);

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 34


Problem Solving & Programming

Program: Write a C program to illustrate the strings.


Source Code:
#include<stdio.h>

int main()

char student_name[25],branch[5],city[15];

printf("Enter name of a student:");

scanf("%[^\n]s", student_name);

printf("Enter branch of a student:");

fflush(stdin); //used to clear the buffer

gets(branch);

printf("Enter city name of a student:");

fflush(stdin);//used to clear the buffer

gets(city);

printf("Student_Name Student_Branch Student_City");

printf("\n%s\t%s\t%s", student_name, branch, city);

Output:

Enter name of a student: Santosh Kumar

Enter branch of a student: CSM

Enter city name of a student: Anantapur

Student_Name Student_Branch Student_City

Santosh Kumar CSM Anantapur

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 35


Problem Solving & Programming

String Handling Functions

Every C compiler supports a large no. of string handling library standard functions,
defined in <string.h> header file. Hence to perform any manipulation on strings, programmer
can use these standard library functions.

1. strlen( ) function
The strlen( ) function calculates the length of a given string. The strlen( ) function takes
a string as an argument and returns its length. The returned value is of type size_t (the
unsigned integer type).
Syntax:
strlen(string);
Example:
char fruit[20] = “Mango”;
strlen(fruit);
strlen(“Mango”);
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 36
Problem Solving & Programming

Program: To find the length of a string


Source Code:

#include<stdio.h>
#include<string.h>
int main()
{
char str1[] = "This is strings program";
printf("Length of str1 = %d ", strlen(str1));
return 0;
}

Output:
Length of str1 = 23

2. strcpy( ) function
The strcpy( ) function copies the source string (including the null character) to the
destination string. The strcpy( ) function also returns the copied string.
Syntax:
strcpy(destination_string, source _string);
Example:
char name1[15] = “Machine Learning”;
char name2[15];
strcpy(name2, name1); // name1 is copied to name2

Program: To copy a string into another string


Source Code:

#include <stdio.h>
#include<string.h>
int main()
{
char str1[30] = "This is copy function", str2[30];
strcpy(str2, str1);
printf("Original String : %s ", str1);
printf("\nCopied String : %s ", str2);
return 0;
}

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 37


Problem Solving & Programming

Output:

Original String: This is copy function


Copied String: This is copy function

3. strncpy( ) function
The strncpy( ) function copies the specified length of source string to the destination string.
The strncpy( ) function also returns the copied string.
Syntax:
strncpy(destination_string, source _string, n);
here, n denotes no. of characters to be copied.
Example:
char name1[15] = “Machine Learning”;
char name2[15];
strncpy(name2, name1, 5); // first 5 characters of name1 is copied to name2

Program:
To copy required no. of characters of a string to another string
Source Code:

#include<stdio.h>
#include<string.h>
int main()
{
char str1[20] = "awesome strncpy", str2[10] = "This is ";
strncpy(str1, str2, 8);
printf("Str1 : %s ", str1);
return 0;
}

Output:

Str1: This is strncpy

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 38


Problem Solving & Programming

4. strcmp( ) function
It compares the two strings and returns an integer value. It is a case-sensitive function.
If both the strings are same (equal) then this function would return 0 otherwise it may
return a negative or positive value based on the comparison.
If string1 < string2 OR string1 is a substring of string2 then it would result in a negative
value.
If string1 > string2 then it would return positive value.
Syntax:
int strcmp(string1, string2);
Example:
result = strcmp(“Good”, “good”);
Note: stricmp( ) function is also similar to strcmp( ) function but this is case-insensitive
function.
Program:
To compare two strings
Source Code:
#include<stdio.h>
#include<string.h>
int main()
{
char str1[20], str2[20];
printf("Enter any two strings:");
gets(str1);
gets(str2);
if(strcmp(str1, str2) == 0)
printf("The strings %s and %s are same ",str1,str2);
if(strcmp(str1, str2) > 0)
printf("The string %s is greater than %s",str1,str2);
if(strcmp(str1, str2) < 0)
printf("The string %s is less than %s ",str1,str2);
return 0;
}

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 39


Problem Solving & Programming

Output:

Enter any two strings: Apple

Apple

The strings Apple and Apple are same

Enter any two strings: Apple

Ball

The string Apple is less than Ball

5. strncmp( ) function
It compares the two strings upto the specified length (no. of characters) and returns an
integer value. It is a case-sensitive function.
If both the strings are same (equal) then this function would return 0 otherwise it may
return a negative or positive value based on the comparison.
If string1 < string2 OR string1 is a substring of string2 then it would result in a negative
value.
If string1 > string2 then it would return positive value.
Syntax:
int strncmp(string1, string2, length);
Example:
result = strncmp(“Good”, “good”,3);
Note: strnicmp( ) function is also similar to strncmp( ) function but this is case-insensitive
function.

6. strlwr( ) function
The strlwr( ) function returns string of characters in lowercase. It is used to convert
uppercase string into lowercase string.
Syntax:
strlwr(uppercase_string);
Example:
strlwr(“COUNTRY”); // returns country

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 40


Problem Solving & Programming

Program:
To convert a string into lowercase string
Source Code:

#include<stdio.h>
#include<string.h>
int main()
{
char str[30] = "THIS IS STRLWR";
printf(" %s ", strlwr(str));
return 0;
}

Output:
this is strlwr

6. strupr( ) function
The strupr( ) function returns string of characters in uppercase. It is used to convert
lowercase string into uppercase string.
Syntax:
strupr(lowercase_string);
Example:
strupr(“country”); // returns COUNTRY

Program:
To convert a given string into uppercase
Source Code:

#include <stdio.h>
#include<string.h>
int main()
{
char str[30] = "this is strupr";
printf("The string in uppercase : %s ", strupr(str));
return 0;
}

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 41


Problem Solving & Programming

Output:

The string in uppercase : THIS IS STRUPR

7. strcat( ) function
The strcat( ) function appends the target string at the end of source string.
Concatenation of two strings can be done by this function. This function returns the
concatenated string.

Syntax:
strcat(string1, string2);
Here, string2 will be joined at the end of string1.
Example:
strcat(“Hello”, “world”);
Note: The strncat( ) function is also similar to strcat( ) function but it concatenates the
string2 to string1 up to the specified length.
Syntax: strncat(string1, string2, length); // length denotes no. of characters to append.

Program:
Program to concatenate two strings.
Source Code:

#include <stdio.h>
#include<string.h>
int main()
{
char str1[30] = "How are ", str2[30] = "you";
strcat (str1, str2);
printf("Str1 : %s ", str1);
return 0;
}

Output:
Str1 : How are you

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 42


Problem Solving & Programming

8. strchr( ) function
The strchr() function finds the first occurrence of a character in a string. The
character c can be the null character (\0); the ending null character of string is included in the
search. The strchr() function returns a pointer to the first occurrence of c that is converted to
a character in string.
Syntax:
char* strchr(char *string, char ch);
Here, *string -> character pointer to the string
ch -> character to be searched
Example:
char *chp = strchr(“Engineering”,’e’);
It returns the address of first occurrence of ‘e’ in “Engineering”.
Note: The function returns NULL if the specified character is not found.
Program: To check whether the given character is present in the string or not
Source Code:
#include <stdio.h>
#include <string.h>
#define SIZE 40
int main( )
{
char buffer1[SIZE] = "computer program";
char *ptr;
char ch = 'p';
ptr = strchr( buffer1, ch );
if(ptr)
printf(“%c is present in %s”, ch, buffer1);
else
printf(“%c is not present in %s”, ch, buffer1);
}

Output:
p is present in computer program

Note: strchr( ) searches the first occurrence of character whereas strrchr( ) searches the last
occurrence of character in the given string.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 43


Problem Solving & Programming

9. strstr( ) function
The strstr( ) function finds the first occurrence of string2 in string1. The function
ignores the null character (\0) that ends string2 in the matching process.
The strstr( ) function returns a pointer to the beginning of the first occurrence
of string2 in string1. If string2 does not appear in string1, the strstr( ) function returns NULL.
If string2 points to a string with zero length, the strstr( ) function returns string1.
Syntax:
char *strstr(char *string1, char *string2);
Example:
char *stp = strstr(“Choclate”, ”ate”);
Program:
To check whether the given string is substring or not.
Source Code:
#include <string.h>
#include <stdio.h>
int main( )
{
char *string1 = "Eating chocolate makes you relaxed";
char *string2 = "ate";
char *result;
result = strstr(string1,string2);
if(result)
printf(“%s is present in %s”, string2, string1);
else
printf(“%s is not present in %s”, string2, string1);
}

10. strrev( ) function


The strrev( ) function returns reverse of the given string.
Syntax:
strrev(string);
Example:
strrev(“Welcome”);

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 44


Problem Solving & Programming

Program:
To print the reverse of a given string
Source Code:
#include<stdio.h>
#include <string.h>
int main()
{
char str[20];
printf("Enter string: ");
gets(str);//reads string from console
printf("String is: %s", str);
printf("\nReverse String is: %s", strrev(str));
return 0;
}
Output:
Enter string: Example
String is: Example
Reverse String is: elpmaxE

11. strset( ) function


strset( ) sets all characters of string, except the ending null character (\0),
to c (converted to a char). The string is a null-terminated string.
strset( ) returns a pointer to the altered string. There is no error return value.

Syntax:
char *strset(char *string, int ch);
Example:
strset(“Password”,’*’); // every character in Password will be replaced by ‘*’
Program:
To illustrate strset( ) function
Source Code:
#include <stdio.h>
#include<string.h>
int main( )

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 45


Problem Solving & Programming

{
char str[20] = "password";
char chr = '*' ;
strset(str, chr);
printf("str: %s ", str);
return 0;
}
Output:
str: ********

Note: strnset( ) function is also similar to strset( ) function but it replaces required no. of
characters. It means if you want to set only n no. of characters by a character, you can do.

Array of Strings
A string is a 1-D array of characters, so an array of strings is a 2-D array of characters.
Just like we can create a 2-D array of int, float etc; we can also create a 2-D array of
character or array of strings. Here is how we can declare a 2-D array of characters.
Array of strings is used to handle and manipulate multiple strings of different sizes.

Syntax:
char str_name[size][max_size];
Here, size -> No. of strings
max_size -> maximum string size
From the given syntax there are two subscripts first one is for how many strings to
declare and the second is to define the maximum length of characters that each string can
store including the null character.
Example:
char str_arr[3][10] = { {‘k’,’i’,’r’,’a’,’n’,’\0’}, {‘v’,’i’,’k’,’a’,’s’,’h’,’\0’},{‘r’,’a’,’v’,’i’,’\0’}};
(or)
char str_arr[3][10] = { “kiran”, ”vikash”, “ravi”};
We already know that the name of an array is a pointer to the 0th element of the array.
The str_arr is a pointer to an array of 10 characters or char(*)[10].
From this, we can conclude that:
(str_arr + 0) points to the 0th string or 0th 1-D array.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 46


Problem Solving & Programming

(str_arr + 1) points to the 1st string or 1st 1-D array.


(str_arr + 2) points to the 2nd string or 2nd 1-D array.
In general, (str_arr + i) points to the ith string or ith 1-D array.
Program:
Write a C program that asks the user to enter a username. If the username entered is one
of the names in the master list then the user is allowed to calculate the factorial of a
number. Otherwise, an error message is displayed.
Source Code:
#include<stdio.h>
#include<string.h>
int factorial(int );
int main( )
{
int i, found = 0, n;
char master_list[5][20] = {"mahesh", "ravi", "lokesh", "akash", "ajith"};
char name[10];
printf("Enter username: ");
gets(name);
for(i = 0; i < 5; i++)
if(strcmp(name, master_list[i]) == 0 )
{
found = 1;
break;
}
if(found==1)
{
printf("\nWelcome %s !\n", name);
printf("\nEnter a number to calculate the factorial: ");
scanf("%d", &n);
printf("Factorial of %d is %d", n, factorial(n));
}

else
printf("Sorry..! %s You are not allowed to run this program.", name);
}
int factorial(int n)
{
int i, fact=1;
for(i=1;i<=n;i++)
fact = fact*i;
return fact;
}

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 47


Problem Solving & Programming

Output:
Enter username: ravi
Welcome ravi !
Enter a number to calculate the factorial: 8
Factorial of 8 is 40320

Enter username: madhav


Sorry..! madhav You are not allowed to run this program.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 48


Problem Solving & Programming

POINTERS
Introduction:

 Variables are used to hold the data values during the execution of a program
 Every variable when declared occupies certain memory locations
 The & operator is used to access and display the address of a variable
 Inorder to store the address of a variable, there is a need of using another variable
which is called Pointer
 A pointer is a derived datatype in C
 Pointers contain memory addresses as their values, hence it is called a memory
variable
Definition:

A pointer is a special variable that stores the address of another variable. Unlike other
variables that hold values of a certain type, pointer holds the address of a variable. For
example, an integer variable holds (or you can say stores) an integer value, however an
integer pointer holds the address of an integer variable. This variable can be of type int, char,
array, function, or any other pointer. The size of the pointer depends on the architecture.

Features of Pointers:
1. Pointers save memory space.
2. Execution time with pointers is faster because data are manipulated with the address,
that is, direct access to memory location.
3. Memory is accessed efficiently with the pointers. The pointer assigns and releases the
memory as well. Hence it can be said the Memory of pointers is dynamically allocated.
4. Pointers are used with data structures. They are useful for representing two-
dimensional and multi-dimensional arrays.
5. An array, of any type can be accessed with the help of pointers, without considering its
subscript range.
6. Pointers are used for file handling.
7. Pointers provide an efficient tool for manipulating data structures such as structures,
linked lists, stacks, queues and trees.
8. Pointers reduce length and complexity of programs.
9. Pointers are used to allocate memory dynamically.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 49


Problem Solving & Programming

Uses of pointers:
1. To pass arguments by reference
2. For accessing array elements
3. To return multiple values
4. Dynamic memory allocation
5. To implement data structures
6. To do system level programming where memory addresses are useful
Disadvantages of Pointers:

 Uninitialized pointers might cause segmentation fault.


 Dynamically allocated block needs to be released explicitly. Otherwise, it would lead to
memory leak.
 If pointers are updated with incorrect values, it might lead to memory corruption.
 Dangling pointers, mostly, create difficult to diagnose errors.
 We can access the restricted memory area.
 Pointers require one additional dereference, meaning that the final code must read the
variable’s pointer from memory, then read the variable from the pointed-to memory.
This is slower than reading the value directly from memory.
 If sufficient memory is not available during runtime for the storage of pointers, the
program may crash
 Basically, pointer bugs are difficult to debug. Its programmer’s responsibility to use
pointers effectively and correctly.

Representation of a variable

Variable Value Address

num 50 687654

Representation of a Pointer variable

Variable Value Address

num 50 687654

pnum 687654 789642

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 50


Problem Solving & Programming

Declaring a pointer
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
A pointer variable must be declared to the type of the value pointed by it.

Syntax:
datatype *pointer_name;
Here,
datatype  any datatype in C
*  dereference operator (asterisk)
pointer_name  any valid identifier in C
Example:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

Important points to remember while declaration:

 The data type of pointer and the variable must match, an int pointer can hold the
address of int variable, and similarly a pointer declared with float data type can hold
the address of a float variable and so on.
 Pointer of any datatype occupies same memory space (in bytes) to the address of a
variable of any datatype.

Initialization of a pointer:
A pointer must be initialized properly to the address of another variable. The
default initial value of a pointer is NULL if it is not initialized.

Syntax:
pointer_name = &variable_name;
Ex:
pnum = &num; /* The pointer pnum is assigned to the address of num. */

Note:
 If a pointer in C is assigned to NULL, it means that it is pointing to nothing.
 The content of the C pointer always be a whole number. i.e; address.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 51


Problem Solving & Programming

It is also possible to combine both declaration and initialization of pointer.


Syntax:
datatype *pointer_name = &variable_name;
Example:
int *iptr = &num;
float *fptr = &avg;
long *pfact = &fact;

Reference operator (&) and Dereference operator (*)

The operator & is called reference operator. It gives the address of a variable.
Likewise, there is another operator that gets the value from the address, it is called a
dereference operator (*). When a pointer is dereferenced, the value at the address stored by
the pointer is retrieved. Normal variables provides the direct access to their values where as
pointer provides indirect access to the values of the variable.

Note: The * sign when declaring a pointer is not a dereference operator. It is just a notation
that it represents a pointer.
Program:
Program to illustrate the concept of Pointers
Source Code:
#include<stdio.h>
int main()
{
int a,*pa;
float b,*pb;
printf("Enter an integer and floating-point number:");
scanf("%d %f",&a,&b);
pa = &a;
pb = &b;
printf("Address of a = %u",&a);
printf("\nAddress of b = %u",pa);
printf("\nValue of a = %d",a);
printf("\nValue of a = %d",*pa);
printf("\n");
printf("\nAddress of b = %u",&b);
Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 52
Problem Solving & Programming

printf("\nAddress of b = %u",pb);
printf("\nValue of b = %f",b);
printf("\nValue of b = %f",*pb);
}

Output:
Enter an integer and floating-point number:64
23.25
Address of a = 6356724
Address of b = 6356724
Value of a = 64
Value of a = 64

Address of b = 6356720
Address of b = 6356720
Value of b = 23.250000
Value of b = 23.250000

Program:

Write a C program to find product of two numbers using pointers

Source Code:

#include<stdio.h>

int main()

int a,b,*pa,*pb;

pa = &a;

pb = &b;

printf("Enter any two integers:");

scanf("%d %d", &a, &b);

printf("Product of two numbers = %d",(*pa * *pb));

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 53


Problem Solving & Programming

Output:

Enter any two integers: 40 20

Product of two numbers = 800

Pointer Arithmetic in C
We can perform arithmetic operations on the pointers like addition, subtraction, etc.
However, as we know that pointer contains the address, the result of an arithmetic operation
performed on the pointer will also be a pointer if the other operand is of type integer. In
pointer-from-pointer subtraction, the result will be an integer value. Following arithmetic
operations are possible on the pointer in C language:
 Increment
 Decrement
 Addition
 Subtraction
 Comparison

Incrementing Pointer in C

If we increment a pointer by 1, the pointer will start pointing to the immediate next
location. This is somewhat different from the general arithmetic since the value of the pointer
will get increased by the size of the data type to which the pointer is pointing.
We can traverse an array by using the increment operation on a pointer which will keep
pointing to every element of the array, perform some operation on that, and update itself in a
loop.

The Rule to increment the pointer is given below:

new_address= current_address + i * sizeof(data type)

Where i is the number by which the pointer get increased.

Note:
For 32-bit int variable, it will be incremented by 2 bytes.
For 64-bit int variable, it will be incremented by 4 bytes.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 54


Problem Solving & Programming

C Pointer Addition/Subtraction
We can add/subtract a value to the pointer. The formula of adding/subtracting value to
pointer is given below:

new_address= current_address +/- (number * size_of(data type))

Note:
For 32-bit int variable, it will add/subtract 2 * number.
For 64-bit int variable, it will add/subtract 4 * number.
Program:
Program to illustrate pointer addition or subtraction
Source Code:
#include<stdio.h>
int main()
{
int a, b,*pa,*pb;
pa = &a;
pb = &b;
printf("Address in pa: %u", pa);
pa = pa + 3; //Adding 3 to the existing address
printf("\nAddress in pa: %u", pa);
printf("\nAddress in pb: %u", pb);
pb = pb - 3; //Subtracting 3 from the existing address
printf("\nAddress in pb: %u", pb);
}
Output:
Address in pa: 6356724
Address in pa: 6356736
Address in pb: 6356720
Address in pb: 6356708

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 55


Problem Solving & Programming

Illegal arithmetic operations with pointers

There are various operations which cannot be performed on pointers. Since, pointer
stores address hence we must ignore the operations which may lead to an illegal address, for
example, addition, and multiplication.

A list of such operations is given below.


 Address + Address = illegal
 Address * Address = illegal
 Address % Address = illegal
 Address / Address = illegal
 Address & Address = illegal
 Address ^ Address = illegal
 Address | Address = illegal
 ~Address = illegal

Pointers and Arrays

When an array is declared, the compiler allocates a base address and sufficient amount
of storage to contain all elements of the array in continuous memory locations.
It is very important to note that, an array name by itself is an address or pointer, since when
we access the address of an array, the address of first element (0th) element is retrieved.
Hence the elements of the array together with their addresses can be displayed by using array
name itself.

Suppose, If we declare an 1D-Array x is as follows:

int x[5] = {10,20,30,40,50};

Assume the base address of x is 2000. The five elements will be stored as follows:

Index X[0] X[1] X[2] X[3] X[4]

Value 10 20 30 40 50

Address 2000 2002 2004 2006 2008

Base Address

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 56


Problem Solving & Programming

We can use array name itself as a pointer, therefore the value of x is 2000. It is the address of
an array.
x = &x[0] = 2000
We can also declare an integer pointer ptr, we can make the pointer ptr that points to an array
x by the following statements.
ptr = x;
(or) ptr = &x[0];

The following table shows the relation between pointers and arrays

Address of each element of an array can be represented by any of the following expressions

Array Pointer
Expression Expression
&x[0] (x+0)

&x[1] (x+1)

&x[2] (x+2)

&x[3] (x+3)

&x[4] (x+4)

Value of each element of an array can be represented by any of the following expressions

Array Pointer
Expression Expression
x[0] *(x+0)

x[1] *(x+1)

x[2] *(x+2)

x[3] *(x+3)

x[4] *(x+4)

Note: The pointer accessing method is much faster than array indexing.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 57


Problem Solving & Programming

Program:
Write a C program to display array elements with their address using array name as pointer.
Source Code:

#include<stdio.h>
int main( )
{
int arr[5] = {10,20,30,40,50};
int idx = 0;
printf("ElementIndex \t Address\t Element");
for(idx=0; idx<5; idx++)
printf("\n arr[%d]\t\t %u\t %d", idx, (arr+idx),*(arr+idx));
}

Output:
ElementIndex Address Element
arr[0] 6356712 10
arr[1] 6356716 20
arr[2] 6356720 30
arr[3] 6356724 40
arr[4] 6356728 50

Program Assignment:

1. Write a C program to find the sum of all elements of an array. Use array name as pointer.

2. Write a C program to display sum of squares and cubes of array elements using pointer.

3. Write a C program to copy elements of one array to another array using pointers.

4. Write a C program to copy elements of one array into another array, order of elements of

stored array should be opposite to first array.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 58


Problem Solving & Programming

Pointers and Two-Dimensional Arrays


A matrix can be represented as a two-dimensional array of elements
In the declaration, first argument is “row_size” and second argument is “column_size”
How to access two dimensional array using pointers?
To access a two dimensional array using pointer, let us recall basics from one
dimensional array. Since it is an array of one dimensional arrays. Suppose I have a
pointer array_ptr pointing at base address of one dimensional array. To access nth element of
array using pointer we use *(array_ptr + n) (where array_ptr points to 0th element of
array, n is the nth element to access and nth element starts from 0).
Pointers can be used to manipulate 2D- arrays, we know two dimensional array is array of
one dimensional array. Hence let us see how to access a two dimensional array through
pointer.
Let us suppose a two-dimensional array
int matrix[3][3];
For the above array,
matrix => Points to base address of two-dimensional array.
Since array decays to pointer.

*(matrix) => Points to first row of two-dimensional array.


*(matrix + 0) => Points to first row of two-dimensional array.
*(matrix + 1) => Points to second row of two-dimensional array.

**matrix => Points to matrix[0][0]


*(*(matrix + 0)) => Points to matrix[0][0]
*(*(matrix + 0) + 0) => Points to matrix[0][0]
*(*matrix + 1) => Points to matrix[0][1]
*(*(matrix + 0) + 1) => Points to matrix[0][1]
*(*(matrix + 2) + 2) => Points to matrix[2][2]
Let’s summarize two dimensional array access using pointer in below image.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 59


Problem Solving & Programming

Program:
Program to access a two dimensional array using pointer.

Source Code:

/* C program to access two dimensional array using pointer. */


#include <stdio.h>
#define ROWS 3
#define COLS 3
/* Function declaration to input and print two dimensional array */
void inputMatrix(int matrix[][COLS], int rows, int cols);
void printMatrix(int matrix[][COLS], int rows, int cols);
int main()
{
int matrix[ROWS][COLS];
int i, j;
/* Input elements in matrix */
printf("Enter elements in %dx%d matrix.\n", ROWS, COLS);
inputMatrix(matrix, ROWS, COLS);
/* Print elements in matrix */
printf("Elements of %dx%d matrix.\n", ROWS, COLS);
printMatrix(matrix, ROWS, COLS);
return 0;
}
void inputMatrix(int matrix[][COLS], int rows, int cols)
{
int i, j;
for(i = 0; i < rows; i++)
{
for(j = 0; j < cols; j++)
{
// (*(matrix + i) + j is equivalent to &matrix[i][j]
scanf("%d", (*(matrix + i) + j));
}
}

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 60


Problem Solving & Programming

}
void printMatrix(int (*matrix)[COLS], int rows, int cols)
{
int i, j;
for (i = 0; i < rows; i++)
{
for (j = 0; j < cols; j++)
{
// *(*(matrix + i) + j) is equivalent to matrix[i][j]
printf("%d ", *(*(matrix + i) + j));
}
printf("\n");
}
}

Output:
Enter elements in 3x3 matrix.
123456789
Elements of 3x3 matrix.
1 2 3
4 5 6
7 8 9
Note:
You can use any of the two notations int matrix[][COLS] or int (*matrix)[COLS], to
access two dimensional array using pointers. The first int matrix[][COLS] is general array
notation. Whereas int (*matrix)[COLS] is a pointer to array.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 61


Problem Solving & Programming

Pointers and Character Arrays (Strings)


A string is a sequence of characters which we save in an array. In C programming language
the \0 null character marks the end of a string.

Creating a string

In the following example we are creating a string str using char character array of size 6.

char str[6] = "Hello";

The above string can be represented in memory as follows.

Creating a pointer for the string

The variable name of the string str holds the address of the first element of the array i.e., it
points at the starting memory address.
So, we can create a character pointer ptr and store the address of the string str variable in it.
This way, ptr will point at the string str.
In the following code we are assigning the address of the string str to the pointer ptr.
char *ptr = str;
We can represent the character pointer variable ptr as follows.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 62


Problem Solving & Programming

The pointer variable ptr is allocated memory address 8000 and it holds the address of the
string variable str i.e., 1000.

Array of Pointers

We can create a two dimensional array and save multiple strings in it.

For example, in the given code we are storing 4 cities name in a string array city.

char city[4][12] = { "Chennai", "Kolkata", "Mumbai", "New Delhi" };

We can represent the city array as follows.

The problem with this approach is that we are allocating 4x12 = 48 bytes memory to the city
array and we are only using 33 bytes. We can save those unused memory spaces by using
pointers

Instead of making each row a fixed no.of characters we can make it as a array of pointers to
strings of varying length as shown below.

char *cityPtr[4] = { "Chennai", "Kolkata", "Mumbai", "New Delhi" };

In the above code we are creating an array of character pointer cityPtr of size 4 to store the
name of the four cities.

We can represent the array of pointers as follows.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 63


Problem Solving & Programming

The above array of pointers can be represented in memory as follows.

The cityPtr pointer variable is allocated the memory address 8000 to 8007. Assuming integer
address value takes 2 bytes space. So, each pointer gets 2 bytes.

Name of the cities are saved in locations 1000, 2000, 3000 and 4000.

Accessing values pointed by array of pointers

To access and print the values pointed by the array of pointers we take help of loop as shown
in the following example.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 64


Problem Solving & Programming

Program:
Program to access multiple strings of an array using array of pointers
Source Code:
#include <stdio.h>
int main(void)
{
// array of pointers
char *cityPtr[4] = {"Chennai", "Kolkata", "Mumbai", "New Delhi"};
int r;
for (r = 0; r < 4; r++) {
printf("%s\n", cityPtr[r]);
}
}
Output:
Chennai
Kolkata
Mumbai
New Delhi
Note:
Ragged Arrays: The character arrays with the rows of varying length are called “Ragged
Arrays”.

Pointers to Pointers (Double Pointers)

A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally,


a pointer contains the address of a variable. When we define a pointer to a pointer, the first
pointer contains the address of the second pointer, which points to the location that contains
the actual value as shown below.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 65


Problem Solving & Programming

A variable that is a pointer to a pointer must be declared as such. This is done by


placing an additional asterisk in front of its name. For example, the following declaration
declares a pointer to a pointer.
Syntax:
datatype **pointer_name;
Example:
int **dpnum;

When a target value is indirectly pointed to by a pointer to a pointer, accessing that value
requires that the asterisk operator be applied twice, as is shown below in the example −

Program:
Program to illustrate double pointers.
Source Code:
#include<stdio.h>
int main( )
{
int num;
int *pnum = &num;
int **dpnum = &pnum;
printf("Enter a number:");
scanf("%d", &num);
printf("Value of num is:%d", num); // using variable name
printf("\nValue of num is:%d", *pnum); //using it’s pointer
printf("\nValue of num is:%d", **dpnum); // using it’s double pointer
}

Output:
Enter a number: 956

Value of num is: 956


Value of num is: 956
Value of num is: 956

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 66


Problem Solving & Programming

Types of Pointers
There are different types of pointers which are as follows −
 Null pointer
 Void pointer
 Wild pointer
 Dangling pointer
Null Pointer
You create a null pointer by assigning the null value at the time of pointer declaration. A null
pointer is a pointer whose initial value is assigned as NULL. This method is useful when you
do not assign any address to the pointer. A null pointer always contains value 0.
Example
Following is the C program for the null pointer −

#include <stdio.h>

int main(){

int *ptr = NULL; //null pointer

printf("The value inside variable ptr is:\n%d",ptr);

return 0;

Output
When the above program is executed, it produces the following result −

The value inside variable ptr is:0

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 67


Problem Solving & Programming

Void Pointer
It is a pointer that has no associated data type with it. A void pointer can hold
addresses of any type and can be typecast to any type. It is also called a generic pointer and
does not have any standard data type. It is created by using the keyword void. The limitation
of void pointers is that the pointed data cannot be referenced directly. Therefore type casting
or assignment must be used to turn the void pointer to a pointer of concrete data type.
Syntax:
void *pointer_name;
Example:
void *vptr;
Program:
Program to illustrate void pointers
Source Code:
#include<stdio.h>
int main( )
{
int p;
float d;
char ch;
void *pt; // Declaration of void pointer
pt = &p;
*(int*)pt = 12;
printf("Value of p = %d", p);
pt = &d;
*(float*)pt = 12.23;
printf("\nValue of d = %f", d);
pt = &ch;
*(char*)pt = 'm';
printf("\nValue of ch = %c", ch);
}
Output:
Value of p = 12
Value of d = 12.230000
Value of ch = m

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 68


Problem Solving & Programming

Wild Pointer
Wild pointers are also called uninitialized pointers, because they point to some
arbitrary memory location and may cause a program to crash or behave badly.
This type of C pointer is not efficient, because they may point to some unknown memory
location which may cause problems in the program. This may lead to the crashing of the
program. It is advised to be cautious while working with wild pointers.
Example
Following is the C program for the wild pointer −

#include <stdio.h>

int main(){

int *p; //wild pointer

printf("\n%d",*p);

return 0;

Process returned -1073741819 (0xC0000005) execution time : 1.206 s

Press any key to continue

i.e. you won’t get output, some compilers show error message at
output

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 69


Problem Solving & Programming

Dangling Pointer

Dangling pointer occurs at the time of the object destruction when the object is deleted
or de-allocated from memory without modifying the value of the pointer. It means It is a
pointer which is pointing to the memory, which is de-allocated. In such cases, the program
will show the undesirable result or may even crash. If the memory is re-allocated to some
other process, then we dereference the dangling pointer will cause the segmentation faults.

In the above figure, we can observe that the Pointer 3 is a dangling pointer. Pointer
1 and Pointer 2 are the pointers that point to the allocated objects, i.e., Object 1 and Object 2,
respectively. Pointer 3 is a dangling pointer as it points to the de-allocated object.

There are three different ways where Pointer becomes a dangling pointer.

1. Deallocation of Memory
Using free( ) function to de-allocate the memory.

Consider the following program


#include <stdio.h>
int main()
{
int *ptr=(int *)malloc(sizeof(int));
int a=560;
ptr=&a;
free(ptr);
return 0;
}

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 70


Problem Solving & Programming

In the above code, we have created two variables, i.e., *ptr and a where 'ptr' is a pointer and 'a'
is a integer variable. The *ptr is a pointer variable which is created with the help
of malloc() function. As we know that malloc() function returns void, so we use int * to
convert void pointer into int pointer.

The statement int *ptr=(int *)malloc(sizeof(int)); will allocate the memory with 4 bytes
shown in the below image:

The statement free(ptr) de-allocates the memory as shown in the below image with a cross
sign, and 'ptr' pointer becomes dangling as it is pointing to the de-allocated memory.

If we assign the NULL value to the 'ptr', then 'ptr' will not point to the deleted memory.
Therefore, we can say that ptr is not a dangling pointer, as shown in the below image:

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 71


Problem Solving & Programming

2. Variable goes out of the scope


When the variable goes out of the scope then the pointer pointing to the variable
becomes a dangling pointer.

Consider the following example

#include<stdio.h>
int main()
{
char *str;
{
char a = ?A?;
str = &a;
}
// a falls out of scope
// str is now a dangling pointer
printf("%s", *str);
}

In the above code, we did the following steps:

 First, we declare the pointer variable named 'str'.


 In the inner scope, we declare a character variable. The str pointer contains the address of
the variable 'a'.
 When the control comes out of the inner scope, 'a' variable will no longer be available, so
str points to the de-allocated memory. It means that the str pointer becomes the dangling
pointer.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 72


Problem Solving & Programming

3. Function call

We will see how the pointer becomes dangling when we call the function.

Consider the following example

#include <stdio.h>
int * fun()
{
int y=10;
return &y;
}
int main()
{
int *p=fun();
printf("%d", *p);
return 0;
}

In the above code, we did the following steps:

 First, we create the main() function in which we have declared 'p' pointer that contains
the return value of the fun().
 When the fun() is called, then the control moves to the context of the int *
fun(), the fun() returns the address of the 'y' variable.
 When control comes back to the context of the main() function, it means the variable 'y' is
no longer available. Therefore, we can say that the 'p' pointer is a dangling pointer as it
points to the de-allocated memory.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 73


Problem Solving & Programming

Pointers and Functions


We can also use a pointer in the context of functions in the following cases

1. Pointers as Function Arguments


2. Functions returning Pointer
3. Pointer to a Function

1. Pointers as Function Arguments

The process of passing pointers as function arguments is called Call-by-reference. This


concept is used when we pass the address of a variable or an array or a string.

When we pass the address of a variable as an argument to a function in the normal


way, the parameters receiving the address should be pointers.
Ex:
void exchange(int*, int*); // Function Declaration
int x, y;
exchange(&x, &y); // Function Call – passing address of variables as function arguments

When an array is passed to a function as an argument, only the address of the first
element (base address) of the array is passed, but not the actual elements of array.

Ex:

void update(char[ ]); // Function Declaration


char name[15];
update(name); // Function call – Passing Base address of an array to the function

2. Functions returning pointer

A function can return a single value by its name.


Ex: c = a+b;
return c;
Since pointers are derived data type in C, we can also force a function to return a pointer
(address) to the calling function.

Consider the following program


Program:
Program to find the largest number among two numbers using pointers.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 74


Problem Solving & Programming

Source Code:
#include<stdio.h>
int* larger(int*, int*); // larger( ) function returns an integer pointer
int main( )
{
int a,b;
int *p;
printf("Enter any two numbers:");
scanf("%d %d", &a, &b);
p = larger(&a, &b); //larger function returns either address of a or b
printf("%d is largest number",*p);
}
int* larger(int *x, int *y)
{
if(*x > *y)
return x; // address of a will be returned
else
return y; // address of b will be returned
}
Output:
Enter any two numbers: 235 487
487 is largest number

3. Pointer to a Function
A function like a variable, has a type and an address location in the memory. Hence it is also
possible to declare a pointer to a function.
A pointer to a function is declared as follows:
Syntax:
data_type (*function_pointer_name)( );
The above declaration tells the compiler that function_pointer_name is a pointer to a function,
which return same data_type value.
Example:
int (*add_ptr)(int, int);

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 75


Problem Solving & Programming

The paranthesis around *function_pointer_name are necessary, because the declaration like
data_type *function_pointer_name( );
would declare function_pointer_ name as a function returning a pointer of some data_type.
We can make a function pointer to point to a specific function by simply assigning the name of
the function to the pointer.
Ex:
double multiply(int, int);
double (*p1)( );
p1 = multiply; // assigning the name of the function to the pointer p1

To call the function multiply( ), we may now use the pointer p1 with the list of parameters.
Ex:
(*p1)(x, y); // Function Call
which is equivalent to multiply(x, y)

Dynamic Memory Allocation


It is required to declare variables that are need to be used in the program in advance,
so that the compiler knows that the variable being used is actually an important part of the
program that the user wants. So, when we declare variables, what the compiler actually does
is allocate memory space to those variables. Now, if you see, this is being done before the
program executes, you can’t allocate variables by this method while the program is executing.
Hence it is called as Static Memory Allocation.
Definition: The mechanism by which storage/memory/cells can be allocated to variables
during the run time is called Dynamic Memory Allocation. In simple words, it is the process of
assigning the memory space during the execution time or the run time.
Note: There are two types of available memories- stack and heap. Static memory allocation
can only be done on stack whereas dynamic memory allocation can be done on both stack and
heap.

Reasons and Advantage of allocating memory dynamically:


1. When we do not know how much amount of memory would be needed for the program
beforehand.
2. When we want data structures without any upper limit of memory space.
3. When you want to use your memory space more efficiently. Example: If you have
allocated memory space for a 1D array as array[20] and you end up using only 10

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 76


Problem Solving & Programming

memory spaces then the remaining 10 memory spaces would be wasted and this
wasted memory cannot even be utilized by other program variables.
4. Dynamically created lists insertions and deletions can be done very easily just by the
manipulation of addresses whereas in case of statically allocated memory insertions
and deletions lead to more movements and wastage of memory.
5. When you want you to use the concept of structures and linked list in programming,
dynamic memory allocation is a must.

Dynamic Memory Allocation Functions

These functions are also called as Memory Management Functions, C provides the
following Dynamic Memory Allocation functions:

1. malloc( )
2. calloc( )
3. realloc( )
4. free( )

Note: To use the above library functions, it is required to include the header file <stdlib.h>

1. malloc( )

 The name "malloc" stands for Memory Allocation.


 malloc( ) will create the dynamic memory with given size and returns the base address
to the pointer. If malloc( ) unable to create the dynamic memory, it will return NULL.
So, it is mandatory to check the pointer before using it.
 malloc( ) doesn't initialize the memory area which is created dynamically. So, the
memory area will have garbage values.
 malloc( ) returns a void pointer, which can be casted into pointers of any form.

Syntax:
void* malloc(size_t size);
where, size_t represents the size of the data type, defined by using sizeof( )
operator
Example:
int *ptr;
ptr = (int*) malloc(sizeof(int));

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 77


Problem Solving & Programming

Program:
Program to illustrate malloc( ) function
Source Code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr;
ptr = (int*) malloc(sizeof(int)); //allocates memory for one integer
if(ptr != NULL)
{
*ptr = 46;
printf("Value entered is:%d",*ptr);
}
else
printf("Memory allocation is unsuccessfull\n");
free(ptr); //deallocates the allocated memory
ptr=NULL; //making pointer as a non-dangling pointer
}
Output:
Value entered is: 46

2. calloc( )
 The name "calloc" stands for contiguous allocation.
 calloc( ) will create the dynamic memory with given size usually used for allocating
memory for arrays.
 It will return the base address of an allocated memory to the pointer variable, on
success. If calloc( ) unable to create the dynamic memory, it will return NULL. So, it is
mandatory to check the pointer before using it.
 The malloc() function allocates memory and leaves the memory uninitialized, whereas
the calloc() function allocates memory and initializes all bits to zero.
 calloc( ) returns a void pointer, which can be casted into pointers of any form.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 78


Problem Solving & Programming

Syntax:
void* calloc(size_t element_count, size_t element_size);
Here,
size_t represents the size of the datatype, defined using sizeof( ) operator
element_count represents no. of elements need to store in an array.
Example:
int *array_ptr;-
array_ptr = (int*)calloc(50, sizeof(int)); // allocates memory for 50 elements and
returns the address of first element.
Program:
Program to illustrate calloc( ) function
Source Code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr,n,i;
printf("Enter no. of elements:");
scanf("%d", &n);
ptr = (int*)calloc(n, sizeof(int));//allocates memory for n integer array
if(ptr != NULL)
{
printf("Enter %d elements one by one:",n);
for(i=0;i<n; i++)
scanf("%d",(ptr+i));
printf("Array Elements are:\n");
for(i=0;i<n; i++)
printf("%d ",*(ptr+i));
}
else
printf("Memory allocation is unsuccessfull\n");
free(ptr);//deallocates the allocated memory
ptr=NULL;//making pointer as a non-dangling pointer
}

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 79


Problem Solving & Programming

Output:
Enter no. of elements: 6
Enter 6 elements one by one: 10 20 30 40 50 60
Array Elements are:
10 20 30 40 50 60

Note: we can also use malloc( ) to allocate memory for arrays but the parameter must be a
single one, hence we can multiply number of elements and size of each element as follows:
int *ptr = (int*)malloc(sizeof(int)*n);

3. realloc( )
 The name "realloc" stands for re-allocation.
 If the dynamically allocated memory is insufficient or more than required, you can
change the size of previously allocated memory using the realloc( ) function. It means
we can resize the memory area which is already created by malloc( ) or calloc( ).
 If realloc( ) request is success, it will return a pointer to the newly allocated memory.
Otherwise, it will return NULL.
 How realloc works?
 realloc( ) will act as malloc( ) if the pointer variable is NULL.
 If the given size is smaller than the actual, it will simply reduce the memory size.
 If the given size is bigger than the actual, it will check whether it can expand the
already available memory. If it is possible it will simply resize the memory.
Otherwise, it will create the new block of memory with the larger size and copy the
old data to that newly allocated memory and then it will deallocate the old memory
area.
Syntax:
void* realloc(void *ptr, size_t new_size);
Here, ptr is a pointer to the previously allocated memory
new_size is size to reallocate
Example:
ptr = (int*) realloc(ptr, 100*sizeof(int));

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 80


Problem Solving & Programming

4. 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.
 It's mandatory to deallocate the memory area which has created dynamically when
the memory is no longer needed.
 If we don't deallocate the dynamic memory, it will reside in the heap section. It is also
called memory leak.
 It will reduce the system performance by reducing the amount of available memory.
 So, it is programmer’s responsibility to deallocate the dynamic memory which is no
longer needed.
Syntax:
void free(void* ptr);
Example:
free(ptr);

Unit – IV Frequently Asked Questions

1. Write a short note on One-Dimensional arrays. [OR]


2. Define an array. What are the different types of arrays? Explain. [OR]
3. What is an array? What are the advantages of arrays over ordinary variables? How arrays
are declared and initialized ?
4. Define a Two-Dimensional array? Explain about its declaration and initialization with an
example?
5. Write a C program to find the sum of all elements in an array.
6. Write a C program to find the product of all the elements in an array?
7. Write a C program to find the sum of all floating point elements in an array.
8. Write a C program to find the smallest element in an array.
9. Write a C program to compute product of two matrices using two-dimensional arrays?
[OR]
Write a C program to perform matrix multiplication using two-dimensional arrays?
10. Explain the methods of passing arrays to functions?
11. Write short notes on pointers. [OR]
What is a pointer? Explain the process of declaring and initializing pointers. Give an
example.

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 81


Problem Solving & Programming

12. What is a pointer? What are the features of pointers? [OR]


What is a pointer? What are the features of pointers? Write a C program to print address
of a variable.
13. Write a C program to show that pointer of any data type occupies same space in
memory.
14. Write a C program to illustrate the process of accessing a variable through its pointer.
15. What are the various arithmetic operations performed on pointers? Explain with an
example? [OR]
Explain about the concept of arithmetic operations with pointers with an example?
16. Explain the relation between an array and a pointer with an example? [OR]
Explain about the concept of Arrays and Pointers with an example?
17. What is an array of pointer? How it declared? Illustrate it with an example?
18. Explain about concept of double pointers with an example? [OR]
How one pointer points to another pointer? Explain?
19. Explain the different ways of using pointers to functions? Explain it with an example for
each? [OR]
Explain how to use pointers as arguments in a function? Explain through an example?
20. What is Dynamic Memory Allocation? Explain about various Dynamic Memory Allocation
functions? Discuss in detail.
21. Define String? Explain how string variables are declared and initialized with an example?
22. Discuss in detail about String handling functions or Built-in string functions with an
example for each? [OR] Explain about any five string handling functions with examples?
23. Explain about the following string handling functions.
strcat( ) b)strcmp( ) c)strlen( ) d)strchr( ) e)strlwr( ) f)strupr( )
24. Explain array of pointers to strings with an example?
25. Write a C program to find the length of a given string using pointers.
26. Write a C program to find whether a given string is palindrome or not.

************

Srinivasa Ramanujan Institute of Technology, Ananthapuramu. Page 82

You might also like