Unit 7 Pointers
Unit 7 Pointers
Pointers
Pointer: Introduction
Pointer is a variable that hold the address of another variable. All the pointer operations are done through two
operators: „*‟ (star) and „&‟ (ampersand). „&‟ (also known address of operator) is a unary operator that returns a
memory address of a variable where as „*‟ (also known as value at address operator) returns value stored at a memory
location stored in a pointer.
Features of Pointer:
It saves the memory space
Execution time is faster because data are manipulated with the address.
It efficiently handles the string data.
It is used with data structure so it is useful for representing two dimensional and multi-dimensional arrays.
It can allocate memory dynamically i.e. it can assign and release the memory space at run time.
Declaration of pointer:
Syntax:
data_type *ptr_variable;
Example:
int *ptr;
It declares the variable ptr as a pointer variable that points to an integer data type i.e. it points to the variable that
holds the integer value.
Initialization of pointer:
Syntax:
ptr_variable = &variable;
Example:
ptr = &x;
#include<stdio.h>
#include<conio.h>
void main()
{
int num=10;
clrscr();
printf("\n Address of the number = %u", &num);
printf("\n Value of number is = %d", num);
getch();
}
Output:
Address of the number = 65524
Value of number is = 10
Here the expression &num returns the address of the variable num. & is “address of” operator. Hence it is displayed
in monitor by using %u, an unsigned integer.
Void pointer:
Let us consider following declaration.
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
1 | Compiled by: Er. M.B. Singh Unit 7: Pointer
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
float num =10.678;
int *ptr;
ptr = #
The statement ptr = &num results an error during compilation of the program. This can be overcome by void
pointer.
A void pointer is a general purpose pointer that can hold address of a variable of any data types i.e. this pointer do not
have any type associated with this and can hold the address of any type of variables. It can be illustrated in following
program.
#include<stdio.h>
#include<conio.h>
void main()
{
int num=10;
float x = 3.14;
void *ptr;
ptr = &x;
printf(“\n %f”, *(float *)ptr);
ptr = #
printf(“\n %d”, *(int *)ptr);
getch();
}
NULL Pointer:
A null pointer is a pointer, which does not point anywhere. A null pointer is a pointer of any type (int, float, char, etc)
that doesn‟t point to any memory location. The integer value zero is used to represent a null pointer.
For example:
int *np = 0;
It is different from a macro NULL. A NULL is a macro defined in the header file “stdio.h” that is used to
represent a null pointer in the source code. A NULL macro has a value zero associated with it.
int *np = NULL;
WAP to perform basic Arithmetic operation of any two numbers, using pointer variable.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,sum,sub,prod;
int *x,*y;
clrscr();
printf("\n Input any two numbers:- ");
scanf("%d%d",&a,&b);
x=&a;
y=&b;
sum = *x + *y;
sub = *x - *y;
prod = *x * *y;
printf("\n Sum = %d, Subtraction = %d and Product = %d", sum,sub,prod);
getch();
}
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
2 | Compiled by: Er. M.B. Singh Unit 7: Pointer
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
WAP to find factorial value of a given number, by using pointer variable.
#include<stdio.h>
#include<conio.h>
void main()
{
int num,i;
long fact = 1;
int *ptr;
clrscr();
printf("\n Input a number:- ");
scanf("%d",&num);
ptr = #
for(i=1;i<=*ptr;i++)
fact*=i;
printf("\n Factorial = %ld", fact);
getch();
}
Handling of 1D array:
There are varieties of ways to access the elements of a 1-D array.
The array elements can be accessed by using the indirection operator directly to the address of a particular element.
The following program illustrates the process:
#include<stdio.h>
#include<conio.h>
void main()
{
int i, num[50], sum = 0;
printf(“\n How many numbers:- “);
scanf(“%d”,&n);
printf(“\n Input %d numbers:- “,n);
for(i=0;i<n;i++)
scanf(“%d”,&num[i]);
for(i=0;i<n;i++)
sum = sum + *(&num[i]);
printf(“\n Sum of the series = %5d”, sum);
getch();
}
The operator &num[i] returns the address of the ith element and *(&num[i]) returns the value at that address.
Another way to access the array elements is to assign the base address to a pointer variable and access the elements
through this pointer variable. It can be shown as in following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int i, num[50], sum = 0,*ptr;
ptr = num; // assigns the address of first element
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
3 | Compiled by: Er. M.B. Singh Unit 7: Pointer
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
printf(“\n How many numbers:- “);
scanf(“%d”,&n);
printf(“\n Input %d numbers:- “,n);
for(i=0;i<n;i++)
scanf(“%d”,(num+i));
for(i=0;i<n;i++)
sum = sum + *(num+i);
printf(“\n Sum of the series = %5d”, sum);
getch();
}
&num[0] Num
&num[1] (num+1)
………………… …………………
&num[i] (num+i)
num[1] *(num+1)
………………… ……………
num[i] *(num+i)
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int *num[10],i;
clrscr();
printf("\n Input any 10 number:- ");
for(i=0;i<10;i++)
scanf("%d",(num+i));
printf("\n The numbers are:\n");
for(i=0;i<10;i++)
printf("%5d",*(num+i));
getch();
}
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
4 | Compiled by: Er. M.B. Singh Unit 7: Pointer
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
1000 1002 1004 1006 1008
2nd 1- D
num[1] array
3rd 1- D
num[2] array
We know that the name of 1-D array gives the base address. Thus num[0] gives the base address of 0th row (In above
case it is 1000). num[1]gives the base address of 1st row (1006 in above case) and num[2]gives the base address of
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
5 | Compiled by: Er. M.B. Singh Unit 7: Pointer
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
2nd row (1012 in above case) i.e. num[i]gives the base address of ith row. The following program shows the output
of the base address of three 1-D array.
#include<stdio.h>
#include<conio.h>
void main()
{
int i, num[][3]={1, 2, 3, 4, 5, 6, 7, 8,9};
for(i=0;i<3;i++)
printf(“\n The base address of %d th row is %u”, i, num[i]);
getch();
}
Output:
The base address of 0th row is 1000
The base address of 1th row is 1006
The base address of 2th row is 1012
Now, the question is how to access a particular element of a 2-D array using pointer? Let us consider that we have to
access the element num[2][1]. As discussed in earlier, num[2] would be the base address of 2nd 1-D array (Say 1012),
then 1012+1 i.e. num[2]+1 would give the address of 1014 and the value at this address can be obtained by an
expression *(num[2]+1). Similarly
From above expression it can be concluded that the value of ith row and jth column can be obtained by the expression
*(num[i]+j).
The following program demonstrated how to receive and print the element of 2-D array with pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, r, c, num[5][5];
printf(“\n Input size of a matrix:- “);
scanf(“%d%d”, &r, &c);
Pointer arithmetic
Pointer arithmetic is one of the powerful features of C language. All the operation cannot be operated on pointer
variables. We can:
Compare pointers
Increment / decrement
Add and subtract integer values from them (i.e. an integer can be added or subtracted from pointer.
Subtract two pointers of same type.
a) Address assignment:
A pointer variable can be assigned the address of an ordinary variable. It is illustrated in following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int num=10, *ptr;
ptr = #
printf(“\n The address of variable num is %u”, ptr);
getch();
}
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
7 | Compiled by: Er. M.B. Singh Unit 7: Pointer
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
b) Assignment of one pointer to another:
A pointer variable can be assigned the content of another variable provided with both pointers points to the same
data type. It is illustrated in following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int num[] = {10,20,30,40, 50}, *ptr1, *ptr2;
ptr1 = &num[0];
ptr2 = ptr1;
getch();
}
Output:
The value of pointer before operation is = 1000
The value of pointer after operation is = 1004
Output:
The value of pointer before operation is = 1200
The value of pointer after operation is = 1196
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
8 | Compiled by: Er. M.B. Singh Unit 7: Pointer
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
ptr1 = &num[0];
ptr2 = &num[4];
printf(“\n The difference of first and last elements is = %u”, ptr2-ptr1);
getch();
}
Output:
The difference of first and last elements is = 4
Here, text + i returns the address of the ith element and *(text+i) returns the value of the ith element. But this method is
not efficient because we cannot edit the string using pointer constant.
It can be eliminated by another method called pointer variable. It can be shown in following program.
#include<stdio.h>
#include<conio.h>
void main()
{
char text[]=”Computer Science”,*ptr;
int i;
ptr=text; //Assigning the base address
printf(“\n The given string is :- “);
for(i=0;i<17;i++)
pritf(“%c”,*(text+i));
getch();
}
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
9 | Compiled by: Er. M.B. Singh Unit 7: Pointer
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
Array of pointers to strings
There is a drawback to store an array of strings, in that the sub arrays that hold the string must all be the same length.
So, that memory space is wasted when strings are shorter than the sub arrays.
#include<stdio.h>
#include<conio.h>
void main()
{
char *weeks[7]= {”Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”,
“Friday”, “Saturday”};
int i;
printf(“\n The days in a week are :- “);
for(i=0;i<7;i++)
puts(weeks[i]);
getch();
}
Double indirection
C is very powerful programming language that can also support a mechanism to create pointer of pointer. It is also
known as chain of pointer. It can be demonstrated in following program.
#include<stdio.h>
#include<conio.h>
void main()
{
int num = 10, *ptr1, **ptr2, ***ptr3;
clrscr();
ptr1 = #
ptr2 = &ptr1;
ptr3 = &ptr2;
printf(“\n The value = %d, %d, %d”, num, *ptr1, **ptr2, ***ptr3);
getch();
}
In above program num is an ordinary variable and holds a value 10. ptr1 is a pointer variable that is holding address of
num i.e. ptr1 is a pointer of num. ptr2 is another pointer variable for pointing to a ordinary variable pointer ptr1.
Similarly ptr2 is another pointer variable that points to another pointer variable ptr1.
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
10 | Compiled by: Er. M.B. Singh Unit 7: Pointer
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
The process of allocating memory at run time i.e. the ability of calculating and assigning the memory space required
by the variable in a program is known as dynamic memory allocation. It provides flexibility in adding, deleting or
rearranging data items at run time i.e. this technique allows us to allocate additional memory space or to release
unwanted space at run time, thus optimizing the use of storage space.
There are four library routines known as “memory management functions” that can be used for allocating and freeing
memory during program execution and they are: calloc(), malloc(), realloc() and free() and their function prototype
are in stdlib.h.
calloc()
The calloc () takes two arguments, the first argument is the number of items and the second argument is size of each
item for which the memory is to be allocated. It also initializes the allocated memory to zero.
Syntax: calloc(number of items, size of each item)
malloc()
The name malloc stands for "memory allocation". The function malloc() reserves a block of memory of specified size
and return a pointer of type void which can be casted into pointer of any form. The malloc() function takes one
argument that specifies the total memory to be allocated. So to allocate memory for n integer, the argument is passed
as n*sizeof(int). It does not initialize the allocated memory and is faster than calloc(). The only difference between
malloc() and calloc() is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of
memory each of same size and sets all bytes to zero.
Syntax of malloc()
ptr =(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with size of byte
size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr=(int*)malloc(100*sizeof(int));
Write a C program to find sum of n elements entered by user. To perform this program,
allocate memory dynamically using malloc() function.
#include <stdio.h>
#include <stdlib.h>
int main()
{
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
11 | Compiled by: Er. M.B. Singh Unit 7: Pointer
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
int n,i,*ptr,sum=0;
printf("\n Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! Memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
realloc()
If the previously allocated memory is insufficient or more than sufficient, then, we can change memory size
previously allocated using realloc().
Syntax of realloc()
ptr=realloc(ptr,newsize);
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
int *ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t", ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=(int *)realloc(ptr,n2);
for(i=0;i<n2;++i)
printf("%u\t", ptr+i);
getch();
}
free()
Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The programmer must
use free() explicitly to release space.
Syntax of free()
free(ptr);
----------------------------------------------------------------------------------------------------------------------------- --------------------------------
12 | Compiled by: Er. M.B. Singh Unit 7: Pointer
----------------------------------------------------------------------------------------------------------------------------- --------------------------------