You are on page 1of 29

Problem Solving Through Programming

using C
Course Code : CSE181106
MODULE : 10 : Pointers
( Lecture – 3 )

Gautam Nath , Assistant Professor


CSE Department
Barak Valley Engineering College , Karimganj

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 1


Topics for today :
 Pointer to Function
 Function returning pointer variables.
 Dynamic allocation / deallocation of
memory
 Notion of Linked List
 Array Vs Linked List
 Advantages / disadvantages of pointers

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 2


Pointer to Function
 As a function parameter pointer is used to hold addresses
of arguments passed during function call. This is also known
as call by reference.

Function Name

void fun(int *a, int *b);

Pointers as Function Parameters

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 3


 When a function is called by reference any change made
to the reference variable will effect the original variable.

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 4


 When a function is called by reference any change made
to the reference variable will effect the original variable.

//pass by reference

#include<stdio.h>
void set(int *ptr)
{
*ptr = 0;//set the argument value to 0
printf("Set() : Inside set function\n");
printf("a = %d\n",*ptr);
printf("&a = %d\n\n",ptr);
}
Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 5
int main()
{
int a = 10;//set the argument value to 10
printf("Main() : Before calling set function\n");
printf("a = %d\n",a);
printf("&a = %d\n\n",&a);
set(&a);
printf("Main() : After calling set function\n");
printf("a = %d\n",a);
printf("&a = %d\n\n",&a);
return 0;
}

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 6


OUTPUT

Main() : Before calling set function


a = 10
&a = 6487580

Set() : Inside set function


a=0
&a = 6487580

Main() : After calling set function


a=0
&a = 6487580

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 7


Functions returning Pointer variables
#include <stdio.h>
int* larger(int*, int*);
void main()
{
int a = 15;
int b = 92;
int *p;
p = larger(&a, &b);
OUTPUT
printf("%d is larger",*p);
} 92 is larger
int* larger(int *x, int *y)
{
if(*x > *y)
return x;
else
return y; }
Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 8
Dynamic allocation / deallocation of memory
Let us consider the static allocation of memory :

#include<stdio.h>
int main()
{
int age[5]={17,19,18,20,21}; /* compile time or static array allocation *
we can't change the array size. * it is always 5. */
return 0;
}

 ifdata size increases more than 5, we have to change the age


array size manually every time.

 If
data size decreases then , we have to reduce the age array size
manually every time to avoid wastage of memory.
Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 9
Dynamic Memory Allocation :

 It can be defined as a procedure in which the size of a data


structure (like Array , Structure , etc ) is changed during the
runtime.

 At runtime, we can create, resize, deallocate the memory


based on our requirement using pointers.

 There are 4 library functions provided by C defined


under <stdlib.h> header file to facilitate dynamic memory
allocation in C programming.They are:
 malloc()
 calloc()
 free()
 realloc()
Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 10
C malloc() method
 Using “malloc” or “memory allocation” function, we can
create memory dynamically at runtime.
 malloc is declared in <stdlib.h> i.e. standard library header file.
 Syntax of malloc
malloc(size in bytes);
 Example
char *ptr;
ptr = malloc(size * sizeof(char));
malloc will take only one argument.
where,
ptr is a pointer. It can be any type.
malloc - used to create dynamic memory
size*sizeof(char) - It will allocate bytes of memory
equivalent to size of data structure X size of data type.

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 11


Example Program :
#include<stdio.h>
#include<stdlib.h> //To use malloc function in our program

int main()
{
int *ptr,size,i;
printf("\nEnter the required size of array :");
scanf("%d",&size);
ptr = malloc(size * sizeof(int));
if(ptr != NULL)
{
//let's get input from user and print it
printf("Enter numbers\n");
for(i = 0; i < size; i++)
scanf("%d",ptr+i);
Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 12
//printing values
printf("The numbers are\n");
for(i = 0; i < size; i++)
printf("%d\n",*(ptr+i)); // *(ptr+i) is as same as
ptr[i]
}
OUTPUT
return 0;
} Enter the required size of array :3
Enter numbers
21
32
42
The numbers are
21
32
42

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 13


Note :
 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.
 malloc doesn't initialize the memory area which is created
dynamically. So, the memory area will have garbage values.

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 14


C calloc() method
 Using “calloc” or “contiguous allocation” function, we
can create memory dynamically at runtime.
 calloc is declared in <stdlib.h> i.e. standard library header file.
 Syntax of malloc
calloc(number of elements, size of the element);
 Example
int *ptr;
ptr = calloc(n,sizeof(int));
calloc will takes two argument.
where,
ptr is a pointer. It can be any type.
calloc - used to create dynamic memory
n - number of elements
sizeof(int)- size of the integer datatype

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 15


Example Program :
#include<stdio.h>
#include<stdlib.h>//To use calloc function in our program

int main()
{
int *ptr,n,i;
printf("\nEnter the required size of array :");
scanf("%d",&n);
ptr = calloc(n,sizeof(int));
if(ptr != NULL)
{
//let's get input from user and print it
printf("Enter numbers\n");
for(i = 0; i < n; i++)
scanf("%d",ptr+i);
Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 16
//printing values
printf("The numbers are\n");
for(i = 0; i < n; i++)
printf("%d\n",*(ptr+i)); // *(ptr+i) is as same as
ptr[i]
}
OUTPUT
return 0;
Enter the required size of array :3
Enter numbers
41
23
37
The numbers are
41
23
37

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 17


Note :
 calloc will create the dynamic memory with given size
and returns the base address to the pointer.
 If calloc unable to create the dynamic memory, it will
return NULL.
 calloc will initialize the memory to zero. So, the allocated
memory area will be set to 0.

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 18


C Realloc() method
 Using realloc function, we can resize the memory area which is
already created by malloc or calloc.
 It's is also declared in stdlib.h library.
 Realloc syntax
realloc(ptr, new size);
Where,
realloc - used to resize the memory area which is
pointed by ptr.
ptr - the name of the pointer variable which needs to
be resized.
new size - the new size of the memory area. It can be
smaller or bigger than the actual size.
 Example : Changing size from 100 bytes to 1000 bytes
char *ptr;
ptr = malloc(100);
ptr = realloc(ptr,1000);
Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 19
Example Program :
#include<stdio.h>
#include<stdlib.h> //To use realloc in our program
int main()
{
int *ptr,i;
//allocating memory for only 1 integer
OUTPUT
ptr = malloc(sizeof(int)); 1
ptr[0] = 1; 2
//realloc memory size to store 3 integers 3
ptr = realloc(ptr, 3 * sizeof(int));
ptr[1] = 2;
ptr[2] = 3;
Note : If the memory area is not
//printing values created dynamically using malloc or
for(i = 0; i < 3; i++) calloc, then the behavior of the
printf("%d\n",ptr[i]); realloc function is undefined.
return 0;
}
Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 20
C free() method
 Using free() we 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.
 free syntax
free(ptr);
Where,
free - used to deallocate the memory area which is
pointed by ptr.
ptr - the name of the pointer variable
 Example :
char *ptr;
ptr = malloc(N); //dynamic memory allocation
free(ptr);
Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 21
Example Program :
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *ptr,n,i,sum = 0;
printf("\nEnter the required size of array :");
scanf("%d",&n);
ptr = malloc(n * sizeof(int));//allocate dynamic memory
printf("\nEnter elements :");
for(i = 0; i < n; i++)
OUTPUT
scanf("%d", ptr + i); Enter the required size of
//add all elements array :3
for(i = 0; i < n; i++)
sum += *(ptr + i); Enter elements :
//print the result 12
printf("sum = %d\n",sum); 20
//deallocate the memory 15
free(ptr); sum = 47
return 0;
}
Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 22
Notion of Linked List
 Linked List is a linear data structure where elements are
not stored at contiguous location.

 the elements are linked using pointers.

 Types of linked lists are


 Singly-linked list,
 Doubly linked list

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 23


Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 24
Array Vs Linked List
Array Linked List
Elements are Stored Elements are Stored
consecutively randomly
It has fixed number of data It can have variable number
items. of data items.
Size is Specified during No need to specify size. It
declaration. can grow and shrink during
execution.
Element location is allocated Element location is assigned
during compile time. during run time.
Memory utilization is not Memory utilization is
efficient efficient

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 25


Array Vs Linked List
Array Linked List
Array takes more time while Linked list takes less time
performing any operation while performing any
like insertion, deletion, etc. operation like insertion,
deletion, etc.
Accessing any element in an Accessing an element in a
array is faster as the element linked list is slower as it
in an array can be directly starts traversing from the
accessed through the index. first element of the linked
list.

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 26


Advantages of pointers

 Provides an alternate way to access array elements


 Pointers provide a way to return more than one value to
the functions
 Reduces the complexity of the program
 Pointers allows us to perform dynamic memory
allocation and deallocation.
 Pointers helps us to build complex data structures like
linked list, stack, queues, trees, graphs etc.

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 27


Disadvantages of pointers

 Dynamically allocated block needs to be freed


explicitly. Otherwise, it would lead to memory leak.

 Pointers are slower than normal variables.

 If pointers are updated with incorrect values, it might lead


to memory corruption.

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 28


End of Syllabus

All the best !

Prepared By - Gautam Nath , Asst Professor , BVEC , Karimganj , Assam 29

You might also like