Chapter 6
Pointer
6.1 Introduction
A pointer is a variable that stores the memory address, possibly, of another variable.
When we say that a pointer variable points to another variable, we mean that it stores the
address of another variable where value is actually stored.
Eg
int *p;
This declaration int *p which is read as p is pointer to integer or int star p is a variable that
holds the address of a variable of type int.
Eg
#include<stdio.h> p a
#include<conio.h> 2293528 5
int main( )
2293528
{
int *p,a=5;
p=&a;
printf("the address of a is %u",p);
printf("\nthe address of a is %u",&a);
printf("\nthe value of a is %d",*p);
printf("\nthe value of a is %d",a);
getch();
return 1;
}
Output:
6.2 Declaration of pointer variable
type *ptrname;
where type is a base type of the pointer and may be any valid data type and ptrname
is a pointer variable and asterisk(*) is indirection operator .
char *ch1, *ch2;
int *p;
float *fp;
6.3 Initializing Pointer
We cannot do anything until you assign a pointer variable a valid address. We use
the address-of(&) operator to get the address of a variable and assign it to the pointer
variable.
Eg
int *p, a=5;
p=&a;
6.4 The Indirection or dereference Operator (getting pointed to value)
When the indirection operator * precedes the name of the pointer variable , it refers
the value of variable pointed to .
Eg
int *p,a=5;
p=&a;
printf(“a=%d”,*p); //gives a=5
*p=10 ; //indirectly changes the value of a to 10
6.5 Chain of pointers(multiple indirection)
We can create a pointer variable that stores the address of another pointer variable
.This situation is called multiple indirection or pointer to [Link] is shown below
int *p1, **p2, a=5;
p1=&a;
p2 is preceded by double indirection operator since it is capable of holding the address of
integer pointer.
p2=&p1; //p2 holds the address of p1.
#include<stdio.h>
#include<conio.h>
int main()
{
int *p1,**p2,a=5;
p1=&a;
p2=&p1;
printf(“%d”,**p2); //gives 5
getch();
return 1;
}
Output:
6.6 Pointer Arithmetic
We can add an integer to pointer, subtract an integer from pointer and subtract two
pointer of same type. These operations are meaningless unless the pointer variable points
to an array element. Besides these no other operations are allowed.
Pointer addition (pointer increment)
Increased by the length of data type that it points to when it finds an increment
operator.
Example:
#include<stdio.h>
#include<conio.h>
int main()
{
int a=10,*b;
b=&a;
printf("Before incrementing the address is %d",b);
b++; //increases the address by the size of int because it holds int type
printf("\nAfter incrementing the address is %d",b);
getch();
return 1;
}
Output
6.7 Pointer and Array
Arrays must be declared or initialized before it is used in the program. Suppose we
declared an array as follows:
int b[ ]={4,8,9,12,10};
Suppose the base address (initial address) of array b[ ] is FFF0
b[0] b[1] b[2] b[3] b[4]
4 8 9 12 10
FFF0 FFF2 FFF4 FFF6 FFF8
If we declare p as an integer pointer then we can make the pointer p to point to the
array b[ ] to the first element of array by following statement :
p=b; this is equivalent to p=&b[0];
Now we can access every element of array b[ ] using p pointer by incrementing it. The
relationship between p and b[ ] is shown below:
p= &b[0]=FFF0
p+1=&b[1]=FFF2
p+2=&b[2]=FFF4
p+3=&b[3]=FFF6
p+4=&b[4]=FFF8
When handling arrays, instead of using array indexing , we can use pointers to
access array elements. The pointer accessing method is much faster then array indexing.
*(p+0) gives same value of b[0]
*(p+1) gives same value of b[1]
*(p+2) gives same value of b[2]
*(p+3) gives same value of b[3]
*(p+4) gives same value of b[4]
Example:
#include<stdio.h>
#include<conio.h>
int main()
{
int *p, b[]={1,2,3,4,5,6,7},i=0;
p=b; //p=&b[0]
printf("Array elements pointed by pointer\n");
while(i<7)
{
printf("%d\t",*(p+i));
i++;
}
getch();
return 1;
}
Output:
Program to read n elements of array and find the sum of elements using pointer.
#include<stdio.h>
#include<conio.h>
int main()
{
int *p,b[100],i,sum=0,n;
printf("Enter the no of element");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter %d element",i+1);
scanf("%d",&b[i]);
}
p=b;
for(i=0;i<n;i++)
sum+=*(p+i);
printf("sum of elements of array is %d",sum);
getch();
return 1;
}
Output:
Exam Questions
[Link] a program to declare two arrays of 10 integers each and get addition of two
arrays into a third and print.
[Link] the above program using pointer.
1.
#include<stdio.h>
#include<conio.h>
int main()
{
int a[]={1,2,3,4,5,6,7,8,9,10},b[]={1,2,3,4,5,6,7,8,9,10},c[10],i;
printf("First array is:\n");
array is:\n");
for(i=0;i<10;i++)
printf("%4d",b[i]);
printf("\nResultant array is:\n");
for(i=0;i<10;i++)
{
c[i]=a[i]+b[i];
printf("%4d",c[i]);
}
getch();
}
Output:
2.
#include<stdio.h>
#include<conio.h>
int main()
{
int a[]={1,2,3,4,5,6,7,8,9,10},b[]={1,2,3,4,5,6,7,8,9,10},c[10],*ap,*bp,*cp,i;
ap=a;//ap=&a[0]
bp=b;
cp=c;
printf("First array is:\n");
for(i=0;i<10;i++)
printf("%4d",a[i]);
printf("\nSecond array is:\n");
for(i=0;i<10;i++)
printf("%4d",b[i]);
printf("\nResultant array is:\n");
for(i=0;i<10;i++)
{
*(cp+i)=*(ap+i)+*(bp+i);
printf("%4d",*(cp+i));
}
getch();
}
Output:
Subtracting Pointer
We can subtract one pointer from another in order to find the number of objects of
their base type that separate the two. The two pointers must be of same type.
Eg
#include<stdio.h>
#include<stdio.h>
#include<conio.h>
int main()
{
int a[]={1,2,3,4,5,6,7,8,9,11},*ap,*bp;
ap=&a[0];
bp=&a[9];
printf("ap=%u\nbp=%u\n",ap,bp);
printf("\nbp-ap=%d",bp-ap);
getch();
return 1;
}
Output
Pointer comparison
Pointer variables can be compared provided both variables are of same data types.
It is useful when both pointer variables points to elements of same array. Let px and py
point to element of same array then px<py means px is pointing to an element ahead of py
and px>=py means px is pointing the element after or same to as py.
What do(px==py), (px!=py) and (px==NULL) mean?
6.8 Rules of pointer operation
The following rules apply when performing operations on pointer variable.
1. A pointer variable can be assigned the address of another variable.
2. A ponter variable can be assigned the values of another pointer variable.
3. A pointer variable can be initialized to NULL or zero value.
4. A pointer variable can be pre-fixed or post-fixed with increment or decrement operators.
5. An integer value may be added or subtracted from a pointer variable.
6. When two pointers point to the same array, one pointer variable can be subtracted from
another.
7. When two pointers point to the objects of same data types, they can be compared using
relational operators.
8. Pointer variable can’t be multiplied by a constant.
9. Two pointer variables can’t be added.
10. A value can’t be assigned to an arbitrary address(ie &x=10, is illegal).
6.9 Pointer and Function
-See in function
6.10 Array, Pointer and Function
Array’s elements can be accessed and modified from the function. It is shown below:
Example:
#include<stdio.h>
#include<conio.h>
void add8(int *);
int main()
{
int math[5]={10,20,30,40,50},i;
printf("Address of array in main function=%u",math); //address of &math[0]
printf("\nBefore executing add8() function\n");
for(i=0;i<5;i++)
printf("%4d",math[i]);
add8(math);
printf("\nAfter executing add8() function\n");
for(i=0;i<5;i++)
printf("%4d",math[i]);
getch();
return 1;
}
void add8(int *m)
{
int i;
for(i=0;i<5;i++)
*(m+i)=*(m+i)+8;
}
Output:
Character pointers and string
Recall a string constant written as “I am a string” is an array of characters. There is
an important difference between definitions
ie
char amessage[ ]= “ this is test”; //an array
char *pmesssage[ ]=”this is test”; //a pointer
Individual characters within the amessage may be changed but amessage will always refers
to same storage. pmesssage is a pointer initialized to point a string constant and it can be
modified to point else where but the result is undefined if we try to modify the string
content.
Illustration
char array[ ]=”hello”;
array h e l l o \0
char *parray[ ]=”hello”;
parray
h e l l o \0
Exam question(2005)
Write a program to reverse of string (character array) using pointer. (5)
#include<conio.h>
#include<stdio.h>
#include<string.h>
int main()
{
char a[20 ],t,*ap;
int i,n;
printf("Enter a string:");
gets(a);
n=strlen(a);
printf("Orginal string in %s\n",a);
ap=a;
for(i=0;i<n/2;i++)
{
t=*(ap+i);
*(ap+i)=*(ap+n-1-i);
*(ap+n-1-i)=t;
}
printf("Reverse of given stirng is: %s", a);
getch();
return 1;
}
Output:
Write a program to find the length of string using pointer
#include<conio.h>
#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
char a[20];
char *ap;
int i=0,n;
printf("Enter a string:");
gets(a);
ap=a;
while(*ap!='\0')
{
i++;
ap++;
}
printf("Length of %s is %d",a,i);
getch();
return 1;
}
Output:
6.12 Pointer and multidimensional arrays
A two dimensional array is actually a collection of one dimensional arrays.
Therefore we can define a two dimensional array as a pointer to a group of contiguous one
dimensional arrays. Thus, a two dimensional array declaration can be written as
data_ type (*ptvar)[expression2];
rather than
data_type array[expression1][expression2];
This concept can be generalized to higher arrays, that is
data_type (*ptvar)[expression2][expression3]……….[expression n];
where
data_type refers to the data type of array
ptvar is the name of pointer variable
array is an array name
expression2…..expression n indicates the maximum no of array elements.
Eg
Suppose x is two dimensional integer array having 10 rows and 20 columns. We declare x
as
int (*x) [20];
rather than
int x[10[20];
In first declaration, x is defined to be a pointer to a group of contiguous one
dimensional, 20 elements integer arrays. Thus x points to the first 20 elements array, which
is actually the first row(i.e row 0) of original two dimensional array. Similarly (x+1) points
to the second 20 element array, which is a second row (row 1) of original two dimensional
array and so on. It is illustrated below
(x+1)
.
.
.
.
(x+9)
The item in the row2 column 5 can be accessed by writing either
x[2][5]
or
*(*(x+2)+5)
(x+2)
*(x+2) *(x+2)+5
*(*(x+2)+5)
Addition of two dimensional matrix using pointer
#include<conio.h>
#include<stdio.h>
int main()
{
int i,j,aa[2][3]={1,1,1,1,1,1},bb[2][3]={2,2,2,2,2,2},cc[2][3],(*a)[3],(*b)[3],(*c)[3];
a=aa;
b=bb;
c=cc;
printf("First matrix is:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%3d",*(*(a+i)+j));
}
printf("\n");
}
printf("Secoond matrix is:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf("%3d",*(*(b+i)+j));
}
printf("\n");
}
printf("The summation of matrix is\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
*(*(c+i)+j)=*(*(a+i)+j)+*(*(b+i)+j);
printf("%3d",*(*(c+i)+j));
}
printf("\n");
}
getch();
return 1;
}
Output:
6.13 Arrays of pointer
There can be array of int, char, float similarly there can be array of pointer. An array of
pointer is nothing but a collection of addresses. Address can be address of variable or
address of array elements.
Example:
#include<stdio.h>
#include<conio.h>
int main( )
{
int *a[4];
int i=31,j=5,k=19,l=71,m;
a[0]=&i;
a[1]=&j;
a[2]=&k;
a[3]=&l;
for(m=0;m<=3;m++)
printf("%d ",*(a[m]));
getch();
return 1;
}
Output:
6.14 Advantages of Pointer
1. Pointers are more efficient in handling arrays and data tables.
2. Pointers can be used to return multiple values from a function.
3. Pointers permit references to functions and thereby facilitating passing of functions as
arguments to other functions.
4. The use of pointer arrays to character strings results in saving of data storage space in
memory.
5. Pointer allows C to support dynamic memory management.
6. Pointers provide an efficient toll for manipulating dynamic data structures such as
structures, link list, queues, stack and tree.
7. Pointers reduce length and complexity of program.
8. They increase the execution speed and thus reduce the program execution time.
6.15 Dynamic memory allocation
The process of allocating memory at run time is known as dynamic memory allocation .
Memory allocation functions
1. malloc( ):-
It allocates the requested size of bytes and returns a pointer to the first byte of the
allocated space. It takes the following form:
ptr=(cast_type*)malloc(byte_size);
where ptr is a pointer of type cast_type. The malloc returns a pointer (of cast_type) to an
area of memory with size byte_size.
Example:
x=(int*)malloc(100*sizeof(int));
A memory space equivalent to 100 times the space of an int bytes is reserved and the
address of the first byte of the memory allocated is assigned to the pointer x of type int.
Similarly,
cptr=(char*)malloc(100);
allocates 10 byte of space for the pointer cptr of type char.
Example:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,j,n,temp,*x;
printf("Enter the no. of elements of an array:");
scanf("%d",&n);
x=(int*)malloc(n*sizeof(int));
printf("Enter the elements of array:");
for(i=0;i<n;i++)
scanf("%d",x+i);
printf("\nOrginal array is\n");
for(i=0;i<n;i++)
printf("%d\t",*(x+i));
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(*(x+i)>*(x+j))
{
temp=*(x+i);
*(x+i)=*(x+j);
*(x+j)=temp;
}
}
printf("\nAscending order array is:\n");
for(i=0;i<n;i++)
printf("%d\t",*(x+i));
free(x);
getch();
return 1;
}
Output:
2. calloc( ):-
While malloc allocates a single block of storage space,calloc allocates multiple blocks of
storage, each of the same size and then sets all bytes to zero. The genereal form of calloc is
ptr=(cast_type*)calloc(n,elem_size);
it allocates contiguous space for n blocks, each of size elem_size bytes.
Example:
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,j,n,temp,*x;
printf("Enter the no. of elements of an array:");
scanf("%d",&n);
x=(int*)calloc(n,sizeof(int));
printf("Enter the elements of array:");
for(i=0;i<n;i++)
scanf("%d",x+i);
printf("\nOrginal array is\n");
for(i=0;i<n;i++)
printf("%d\t",*(x+i));
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
if(*(x+i)>*(x+j))
{
temp=*(x+i);
*(x+i)=*(x+j);
*(x+j)=temp;
}
}
printf("\nAscending order array is:\n");
for(i=0;i<n;i++)
printf("%d\t",*(x+i));
free(x);
getch();
return 1;
}
Output:
Releasing the used space: free( )
With the dynamic run time allocation, it is our responsibility to release the space when
it is not required. The release of storage space becomes important when the storage is
limited. The general form is
free(ptr);
prt is a pointer to a memory block, which has already been created by malloc or calloc.
Altering the size of a block realloc( ):-
The general form of realloc( ) is
ptr=realloc(ptr, newsize);
ptr=malloc(size);
relocation is done by
ptr=realloc(ptr, newsize);
Example:
#include <stdio.h>
#include<conio.h>
#include <stdlib.h>
int main() {
int *arr;
int n, new_n;
int i;
printf("Enter initial size of array: ");
scanf("%d", &n);
arr = (int *)malloc(n * sizeof(int));
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", arr+i);
}
printf("Enter new size of array: ");
scanf("%d", &new_n);
arr = (int *)realloc(arr, new_n * sizeof(int));
if (new_n > n) {
printf("Enter %d more elements:\n", new_n - n);
for (i = n; i < new_n; i++) {
scanf("%d", arr+i);
}
}
printf("Array elements are:\n");
for (i = 0; i < new_n; i++) {
printf("%d ", *(arr+i));
}
free(arr);
getch();
return 0;
}
Output:
void Pointer:
A void pointer (void *) in C is a generic pointer that can store the memory address of any data
type. It is often referred to as a "typeless pointer" because it has no associated data type, making
it a versatile tool for general-purpose programming.
Example:
#include<stdio.h>
#include<conio.h>
int main()
{
int a=5;
float b=10.5;
char c='a';
double d=20.55;
void *p;
p=&a;
printf("Tnteger value is %d\n",*(int*)p);
p=&b;
printf("Float value is %f\n",*(float*)p);
p=&c;
printf("Character value is %c\n",*(char*)p);
p=&d;
printf("Double value is %f\n",*(double*)p);
getch();
return 1;
}
Output:
NULL pointer:
A null pointer is a pointer assigned the value of a null pointer constant, which is typically the
macro NULL or the integer literal 0.
Declaration and Initialization: A pointer can be declared and initialized as a null pointer using
the NULL macro or 0:
#include <stddef.h> // Header file where NULL is defined
int main()
{
int *ptr = NULL; // Recommended practice
// or
char *str_ptr = 0; // Also valid
…..
…..
getch();
return 1;
}
Assignment: [Submission Deadline: 2082/09/21]
1. What is a pointer? Explain with suitable example.
2. What is chain of pointers? Explain with suitable example.
3. What is pointer arithmetic? Also mention the rules of pointer operations.
4. Write a program to find the sum of the elements of integer array using pointer.
5. What is dynamic memory allocation? Explain with suitable example.
6. How can memory of a variable be initialized dynamically. Explain with example.
7. Write a program to sort n elements of array using pointer.
8. Write a program to find the length of a string using pointer.
9. Write a program to arrange a given string in alphabetic order using pointer.
10. Explain about array of pointer s and pointer to array with suitable program.
11. Write a program to sort n numbers using pointer. [Hint: Use DMA]
12. Write a program to sort n numbers using pointer and function.
13. Write a program to read n numbers and find the third largest number using pointer.
14. Write a program to find the sum of all elements of a given matrix using pointer.
15. Write short notes on
a. NULL pointer
b. void pointer
c. Memory leak
d. malloc() vs calloc() vs realloc()
e. free()
f. static vs dynamic memory allocation
g. Wild pointer
h. Dangling pointer
i. Out of bound pointer