CHAPTER 8
pointer
prepared by: Shiva pd. Mahato
Introduction to pointer
A pointer is a variable which holds the memory address of a variable. A pointer is a memory
variable that stores a memory address.
Pointer can have any name that is legal for other variable and is declared in the same fashion
like other variable but it is denoted by ‘*’ operator.
So a pointer can be represented by combination of *(asterisk) with a variable. It is possible
access to and display address of the memory location of variable using & operator with
variable name.
The general syntax for declaration for pointer is
Data_type *pointer_variable;
This decleration tells the compiler three things about the variable pointer_variable.
The asterisk tells that the variable pointer_variable is a pointer variable name.
pointer_variable. needs memory location
pointer_variable points to a variable of type data type.
For example:
int *pnum; char *pch; float *pfnum;
int qty= 76;
int *ptr = qty; ptr=&qty;
This statement instructs the system to find a location for the integer variable qty and puts the
value 76 in that location.
prepared by: Shiva pd. Mahato
Introduction to pointer
Suppose system choose the address location 6000 for qty. During execution, the system
associates the name qty with the address 6000(this is similar to something to having a house
number as well as the house name).
We may access to the value 76 by using either the name qty or the address 6000.
[A pointer is therefore, nothing but a variable that contains an address which is a location of
another variable in memory.]
Initialization of pointer:
Like ordinary variables are initialized within the declaration part, pointer variables can also be
initialized by assigning the address of another variable that is being used in the program.
Making pointer variable to point other variable by providing address of that variable is known
as pointer referencing or initialization of pointer.
The syntax is;
Data type *ptr_var = expression;
Where,
data type → is a basic data type
*ptr_var →a pointer
expression →may be a constant or any other variable
prepared by: Shiva pd. Mahato
Introduction to pointer
or,
Data type *ptr_var ;
prt_var=&variable;
Where,
data type → is a basic data type
*ptr_var →a pointer
&varibale →may be a constant or address of any other norval variable.
Example:
#include<stdio.h>
int main()
{ int x=5;
int *ptr;
ptr=&x; //referencing
printf(" The value of x=%d\n", *ptr);
*ptr=421;
printf(" The value of x after initialization of pointer =%d\n", *ptr);
return 0;
}
Output:
The value of x= 5
The value of x after initialization of pointer =421
prepared by: Shiva pd. Mahato
Introduction to pointer
Dereference pointer:
This is the process of pointing the contents of variables by pointer variable indirectly. Steps
involved in dereferencing are:
i. Address of a variable, whose value to be referenced, is assigned to a pointer.
ii. Then, this pointer points to the value.
#include<stdio.h>
int main()
{
int x,y;
int *ptr;
x = 5;
ptr = &x;
y = *ptr;
printf("%d\n", y);
return 0;
}
The integer x has a value of five. The pointer ptr gets the address of integer x.
The value pointed to is *ptr. (in this case five). So the integer y now contains the value of five.
The * is used to dereference a pointer.
prepared by: Shiva pd. Mahato
Introduction to pointer
#include<stdio.h>
int main()
{
int num, *pnum;
pnum = #
printf(“\n Enter the number : “);
scanf(“%d”, &num);
printf(“\n The number that was entered is : %d”, *pnum);
return 0;
}
OUTPUT:
Enter the number : 10
The number that was entered is : 10
prepared by: Shiva pd. Mahato
Pointer arithmetic:
A pointer variable holds the address of the variable. This address can be incremented or
decremented.
But the multiplication and division operations cannot be performed on these addresses. Thus,
the possible arithmetic operations on pointer variable are increase, decrement, prefix and
postfix.
Operations which are performed on pointer variables are;
Addition and subtraction
An integer value can be added to and subtracted from a pointer variable.
For example; int *ptrx;
ptrx=ptrx+2; ptrx=ptrx-2; ptrx++; ptrx--;
We can compare pointers by using relational operators in the expressions. For example p1 >
p2 , p1==p2 and p1!=p2 are all valid in C.
When using pointers, unary increment (++) and decrement (--) operators have greater
precedence than the dereference operator (*).
Therefore, the expression
*ptr++ is equivalent to *(ptr++). So the expression will increase the value of ptr so
that it now points to the next element.
prepared by: Shiva pd. Mahato
Array and pointer:
An array name in C is very much like a pointer but there is difference between each other.
The pointer is a variable that can be appear on the left hand side of an assignment operator
and the array name is a constant and cannot be appear on the left hand side of an assignment
operator.
Relationship between one dimension array and pointer:
Since the name of the array itself represents the address or memory location of first elements
of the array.
So, Array is called constant pointer i.e. we can use pointer in array without declaring the
pointer variable.
Arrays and pointers have a special relationship as arrays use pointers to reference memory
locations.
C Language treats the name of the array as if it were a pointer to the first element. This is
important in understanding how to do arithmetic with arrays.
Hence, in case of array pointer can be used in two ways:
Using array name itself as a pointer
Using pointer variable by pointing the address of array elements
prepared by: Shiva pd. Mahato
Array and pointer:
Using array name itself as a pointer:
While using the array name itself as a pointer, it is not necessary to declare the pointer variable as
int *p;
Consider int x[5];
The name x is defined as a constant pointer pointing the address of first element x[0] of the array.
Therefore ,x and &x[0] is same. Since array subscripting is defined in terms of pointer arithmetic.
That is x[i] is defined to be same as *((x)+i);
Which is same as *(&x[0]+(i));
Thus, &x[i] and (x+i) both represents the address of the ith element of array and, x[i] and *(x+i)
both represents the contents of that address.
#Write a program to enter five numbers and store them in array. Display the contents
of array. Use array name itself as a pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i;
printf(“enter five numbers to be stored in array\n”);
for(i=0;i<=4;i++)
{ scanf("%d",(a+i));
}
prepared by: Shiva pd. Mahato
Array and pointer:
Printf(“The contents of the array are\n”);
for(i=0;i<=4;i++)
{
printf("%d\t",*(a+i);
}
getch();
}
Output:
prepared by: Shiva pd. Mahato
Array and pointer:
#Write a program to enter five numbers and store them in array and find the sum of all elements of
array. Use array name itself as a pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i;
int sum=0;
for(i=0;i<=4;i++)
{
scanf("%d",(a+i));
sum=sum+ *(a+i);
}
printf("%d",sum);
getch();
}
prepared by: Shiva pd. Mahato
Array and pointer:
Using pointer variable by pointing the address of array elements:
Consider int x[5], *p;
The name x is defined as a constant pointer pointing to the address of first element x[0] and p is
declare as a integer pointer, then we make the pointer p to point the array x by the following
assignment statement,
p=x;
is same as, p=&x[0];
After assigning the address of first element of array x to pointer variable p, we can replace the array
name with pointer variable p to represent the address and content of the array.
Thus, (p+i) represents the address of the ith element of array and *(p+i) represents the contents
(value stored in array) of that address.
#Write a program to enter five numbers and store them in array. Display the contents of array. Using
pointer variable.
#include<stdio.h>
#include<conio.h>
void main()
{ int a[5 ],i,*p;
p=a; /* or p=&a[0]; */
printf(“enter five numbers to be stored in array\n”);
for(i=0;i<=4;i++)
{ scanf("%d",(p+i));
}
prepared by: Shiva pd. Mahato
Array and pointer:
Printf(“The contents of the array are\n”);
for(i=0;i<=4;i++)
{
printf("%d\t",*(p+i);
}
getch();
}
Output:
#Write a program to enter five numbers and store them in array and find the sum of all elements of array.
Use array name itself as a pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i;
int sum=0;
for(i=0;i<=4;i++)
{
scanf("%d",(a+i));
sum=sum+ *(a+i);
}
printf("%d",sum);
getch();
} prepared by: Shiva pd. Mahato
Array and pointer:
Using pointer variable by pointing the address of array elements:
Consider int x[5], *p;
The name x is defined as a constant pointer pointing to the address of first element x[0] and p is
declare as a integer pointer, then we make the pointer p to point the array x by the following
assignment statement,
p=x;
is same as, p=&x[0];
After assigning the address of first element of array x to pointer variable p, we can replace the array
name with pointer variable p to represent the address and content of the array.
Thus, (p+i) represents the address of the ith element of array and *(p+i) represents the contents
(value stored in array) of that address.
#Write a program to enter five numbers and store them in array. Display the contents of array. Using
pointer variable.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,*p;
p=a; /* or p=&a[0]; */
printf(“enter five numbers to be stored in array\n”);
for(i=0;i<=4;i++)
{
scanf("%d",(p+i));
} prepared by: Shiva pd. Mahato
Array and pointer:
Printf(“The contents of the array are\n”);
for(i=0;i<=4;i++)
{
printf("%d\t",*(p+i);
}
getch();
}
prepared by: Shiva pd. Mahato
Array and pointer:
Write a program to merge two sort arrays in to third arrays using pointer.
#include<stdio.h>
#include<conio.h>
void main( )
{int,*p,*q,*r;
int a[5]={2,3,4,5,6},b[5]={7,8,9,10,11},c[10];
p=&a[0];
q=&b[0];
r=&c[0];
for(i=0;i<=4;i++)
{
*(r+i)=*(a+i);
}
for(i=5;i<=9;i++)
{
*(r+i)=*(b+i);
}
printf(“the merged array are\n”);
for(i=0;i<=9;i++)
{
printf(“%d\t”, *(r+i));
}
getch( );
}
prepared by: Shiva pd. Mahato
Array and pointer:
Write the program to read set of n numbers from user and store them in array display them in ascending
order using array name itself as a pointer.
#include<stdio.h>
#include<conio.h>
void main ( )
{
int i ,j ,a[100],b;
clrscr( );
printf(“\nEnter the number of elements to be stored in array: “);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{ printf(“enter the %d th number”,i+1);
scanf(“%d”,(a+i));
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{ if(*(a+i)<*(a+j))
{
b=*(a+i);
*(a+i)=*(a+j);
*(a+j)=b;
}
}
}
prepared by: Shiva pd. Mahato
Array and pointer:
printf(“\Array elements in ascending order:”);
for(i=0;i<n;i++)
printf(“%d\t”,*(a+i));
getch( );
}
WAP to read n numbers in array and reverse them using user defined function and pointer.
#include<conio.h>
#include<stdio.h>
void reverse(float *p, int n);
void main()
{ float a[30],*p;
int i,n;
clrscr();
p=&a[0];
printf("enter how many numbers in array\n");
scanf("%d",&n);
printf("enter %d numbers\n ",n);
for(i=0;i<n;i++)
{
scanf("%f",p+i); prepared by: Shiva pd. Mahato
Array and pointer:
reverse(p,n);
printf(" The reverse array are\n");
for(i=0;i<n;i++)
{printf("%f\t",*(p+i));
}
getch();
}
void reverse(float *p,int n)
{ float t;
int i;
for(i=0;i<n/2;i++)
{ t=*(p+i);
*(p+i)=*(p+n-1-i);
*(p+n-1-i)=t;
}
}
Output:
enter how many numbers in array
5
prepared by: Shiva pd. Mahato
Pointer and multidimensional array:
enter 5 numbers
1
2
3
4
5
The reverse arrays are
5 4 3 2 1
A two dimensional array for example is actually a collection of one dimensional arrays. Therefore, we define
a two dimensional array as a pointer to a group of contiguous one dimensional array. Thus two dimensional
arrays can be declared as
Data_type (*ptvar)[expr1];
Similarly, three dimensional arrays can be declared as
Data_type (*ptvar)[expr1][expr2];
int (*p)[3];
this decleration is same as int p[][3]; and q is a pointer to an array of 4 integer.
Here, p-> pointer to first row
p+i -> pointer to ith row
*(p+i) -> pointer to first element in ith row
*(p+i)+j -> pointer to jth element in ith row
*(*(p+i)+j) -> value stored in ith row and jth column
prepared by: Shiva pd. Mahato
Pointer and multidimensional array:
Write the program to input two 3*3 matrixes and multiply them and display the result in matrix form
using pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
int (*a) [3],(*b)[3],(*c)[3],i,j,k;
clrscr();
printf("Enter the element of First Matrix:\n");
for(i=0;i<=2;i++){
for(j=0;j<=2;j++){
scanf("%d",(*(a+i)+j))
}
}
printf("Enter the element of Second Matrix:\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++){
scanf("%d",(*(a+i)+j));
}
}
prepared by: Shiva pd. Mahato
Pointer and multidimensional array:
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{ *(*(c+i)+j)=0;
for(k=0;k<=2;k++)
{
*(*(c+i)+j)=*(*(c+i)+j)+ *(*(a+i)+k)+*(*(b+k)+j);
}
}
}
printf("The Multiplication of two Matrix is\n");
for(i=0;i<=2;i++){
for(j=0;j<=2;j++){
printf("%d\t",",*(*(a+i)+j));
}
printf("\n");
}
getch();
}
prepared by: Shiva pd. Mahato
Pointer and multidimensional array:
Write a program to read a matrix of m*n and print their transpose.
#include<stdio.h>
#include<conio.h>
void main()
{ int a[50][50],i,j,temp,m,n,*p;
clrscr();
p=&a[0][0];
printf("enter the oder of matrix");
scanf("%d%d",&m,&n);
printf("enter the matrix of order %d*%d\n",m,n);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{ scanf("%d",(p+(i*50)+j));
}
}
printf("The input matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{ printf("%d\t",*(p+(i*50)+j));
}
prepared by: Shiva pd. Mahato
printf("\n");
Pointer and multidimensional array:
for(i=0;i<m;i++)
{
for(j=0;j<=i;j++)
{ temp=*(p+(i*50)+j);
*(p+(i*50)+j)=*(p+(j*50)+i);
*(p+(j*50)+i)=temp;
}
}
printf("The transpose matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{ printf("%d\t",*(p+(i*50)+j));
} printf("\n");
}
getch();
}
prepared by: Shiva pd. Mahato
Pointer and multidimensional array:
Comparison of Array and Pointer:
Array Pointer
Array is collection of homogenous element i.e. Pointer is special type of variable which is used
of similar data types. to store the address of another ordinary variable.
Array
Array uses index/subscript for accessing array After referencing, i.e after initialization of
elements. pointer, pointer uses dereferencing or value-at (*)
operator to access values.
Name of the array is equivalent to address of We need to declare pointer variable to point
first element of that array. So name of array another variable using: data_type
points to the first element of array and acts like *name_of_pointer_variable;
pointer variable. Due to this, array is also
considered as indirect pointer or constant
pointer.
General syntax for declaring array is: data_type General syntax for declaring pointer is: data_type
name_of_array[size_of_array]; For example: *name_of_pointer variable; For example: int
int a[30]; float b[4][4]; *ptr; float *fptr; char *cptr;
prepared by: Shiva pd. Mahato
call by value call by reference:
Difference between call by value and call by reference:
The C language is a “call by value” language, which means that the called function is given a copy of its arguments, and
doesn’t know their addresses.
(For example myfunction(x) call is given, the value of x is passed, not its address). This makes it impossible to change
the value of x from the inside of the function (myfunction).
prepared by: Shiva pd. Mahato
call by value call by reference:
call by value call by reference
In call by value, value of the actual argument is In call by reference, address of the actual argument is
passed in the function call. passed in the function call.
In call by value, only one value can be returned In call by reference, multple value can be returned
from user defined function to calling portion of the from user defined function to calling portion of the
program using return statement. program without using return statement.
Any change made in the formal argument does not Any change made in the formal argument is reflected
affect the actual arguments because formal back to the actual arguments. That is, Any change that
arguments are photocopy of actual arguments. is made to the data item will be recognized in both the
function and calling portion program
#include<stdio.h> #include<stdio.h>
#include<stdio.h> #include<stdio.h>
void swapping(int c, int d); void swapping(int *c, int *d);
void main(void) void main(void)
{ int a=5,b=6; { int a=5,b=6;
printf(" Before passing to a function\n "); printf(" Before passing to a function\n ");
printf(" a=%d\tb=%d \n", a, b); printf(" a=%d\tb=%d \n", a, b);
swapping(a,b); swapping(&a,&b);
printf(" Affter passing to a function\n "); printf(" Affter passing to a function\n ");
printf(" a=%d\tb=%d \n", a, b); printf(" a=%d\tb=%d \n", a, b);
getch(); getch();
} }
void swapping(int c, int d) void swapping(int *c, int *d)
{ {
int tmp; int tmp;
tmp = c; tmp = *c;
c = d; *c = *d;
d = tmp; d = *tmp;
} }
Output: Output:
Before passing to a function Before passing to a function
a=5 b=6 a=5 b=6
Affter passing to a function Affter passing to a function
a=5 b=6 a=6 b=5
prepared by: Shiva pd. Mahato
Pointer to a pointer
Pointer to Pointer:
The pointer variable containing address of another pointer variable is called as pointer to pointer.
For example: int value, *ptr1,**ptr2;
Where ptr2 is the pointer to the pointer and is used to holds the address of pointer variable ptr1.
Program example:
#include<stdio.h>
void main()
{
int value,*ptr1,* *ptr2
value=125;
printf(“value=%d\n”,value);
ptr1=&value;
ptr2=&ptr1;
printf(“using ptr1 value=%d\n”,*ptr1);
printf(“using ptr2 vale =%d\n”,**ptr2);
}
Output:
Value=125
Using ptr1 value=125
Using ptr2 value=125 prepared by: Shiva pd. Mahato
Array of pointer:
Array of pointer:
C language also supports array of pointers. It is nothing but collection of address.
For example, int *ptr[10]; where ptr is the array of pointer and it stores the address of 10 variable.
Program:
#include<stdio.h>
void main()
{
int *arrp[3];
int arr1[3]={5,10,15};
for (k=0;k<3;k++)
{arrp[k]=arr1+k;
}
for(k=0;k<=3;k++)
printf(“d\t”,*arrp[k]);
}
Output:
5 10 15
prepared by: Shiva pd. Mahato
Pointer and string:
Pointer and string:
Many string operations in C are usually performed by using pointer to the array and using
pointer arithmetic. Strings are one dimensional array of type char. In C, string is terminated by
a null character (‘\0’).
#include<stdio.h>
#include<conio.h>
#include<string.h>
int display(char *p);
void main()
{
int nch;
char a[200];
clrscr();
puts("Enter a text\n");
gets(a);
nch=dispay(a);
printf(“length of the string=%d\n”,nch);
getch();
} prepared by: Shiva pd. Mahato
Pointer and string:
int display(char *p)
{ int l=0;
while(*p!=’\0’)
{ l++;
P++;
}
return (l);
}
WAP to read a string and print it reverse using user defined function and pointer.
#include<conio.h>
#include<stdio.h>
void reverse(char *a);
main()
{
char a[30],*p;
clrscr();
p=&a[0];
printf("enter string");
gets(p);
prepared by: Shiva pd. Mahato
reverse(p);
Pointer and string:
puts(p);
getch();
}
void reverse(char *p)
{ int len=0,i=0;
char temp;
while(*(p+i)!='\0')
{ len++;
i++;
}
for(i=0;i<len/2;i++)
{ temp=*(p+i);
*(p+i)=*(p+len-1-i);
*(p+len-1-i)=temp;
}
}
prepared by: Shiva pd. Mahato
Pointer advantages:
Features of pointer:
Pointer save memory
Execution time with pointer is faster because data is manipulated with the address i.e. direct
access to memory location.
Pointer reduce the length and complexity of the program
The memory is efficiently access with the pointer using DMA
Uses of pointer:
Accessing array elements.
Passing arguments to function by reference
prepared by: Shiva pd. Mahato
Dynamic memory allocation:
The memory allocation may be classified as a static allocation and dynamic allocation.
In static, allocation, size of the memory may be required for calculation that must be defined
before loading and execution the program.
In dynamic allocation, the required memory size is allocated while program is executing.
There is a technique by which program can be obtained storage space in the main memory
during the execution of program is called dynamic memory allocation.
In this method, space for the program is allocated from the free space during execution of
program. The free space of the memory is called heap.
malloc() function:
This function is used to allocate memory space in bytes to the variables of different data types.
This function reserves bytes of determined size and return base address to pointer variable.
The prototype are declared in header file <alloc.h>
It syntax is
data_type *ptr;
ptr=(data_type *)malloc((sizeof(data_type)*n);
the allocated region is not filled with zeros. The starting address is returned if the function is
successful.
A zero is returned if the function attempt to get a block of memory fail.
prepared by: Shiva pd. Mahato
Dynamic memory allocation:
calloc():
The calloc() function is used to allocate the continuous memory or element by element basis.
The name stands for calculated allocation. It is useful for arrays and array like structures
whrere continuity of memory is required. Some version automatically full memory zeros. The
starting address of the area is returned if the function is successful. A zero is returned if the
function attempt to get a block of memory fails.
The syntax is:
data_type *ptr;
ptr=(data_type *)calloc((sizeof(data_type)*n),2);
Difference between malloc() and calloc()
malloc() stands for memory allocation Calloc() stands for contiguos memory allo
cation
It allocates single block of memory of it allocates a multiple block of memory of
Specified size. Same size.
The malloc() contains one argument The calloc() contains two arguments i.e (num
ie (size of data type) ber of elemnts and size of memory
It initialize the allocated memory with It initialize the allocated memory with zero
Non zero value
it is faster than calloc() function it is slower than malloc() function
prepared by: Shiva pd. Mahato
Dynamic memory allocation:
realloc():
The realloc() function is used to increase or decrease the size of the block of heap memory to
the size specific by size while preserving the address and contents of the beginning of the
block. The function realloc() can diminish the size of the allocated area.
data_type *ptr;
ptr=(data_type *)malloc(sizeof(data_type)*n);
ptr=(data_type *)realloc(ptr, sizeof(data_type)*n);
free() function
This function frees a block of allocated memory. Its syntax is as follows
free(p);
where p is a pointer which indicates the beginning of the block.
prepared by: Shiva pd. Mahato
Dynamic memory allocation:
Write the program to read set of n numbers from user dynamically and passed
them in function and display them in ascending.
#include<stdio.h>
#include<conio.h>
void sorting(int *p, int n); // function prototype
void main ( )
{
int i ,j ,*p,n;
clrscr( );
printf(“\nEnter the number of elements to be stored in array: “);
scanf(“%d”,&n);
p=(int*)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
{ printf(“enter the %d th number”,i+1);
scanf(“%d”,(p+i));
}
prepared by: Shiva pd. Mahato
Dynamic memory allocation:
void sorting(int *p,int n) //called function
{ int b;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{ if(*(p+i)<*(p+j))
{
b=*(a+i);
*(p+i)=*(p+j);
*(b+j)=b;
}
}
}
}
prepared by: Shiva pd. Mahato
Dynamic memory allocation:
Program to enter name of n person display in alphabetical order using DMA
#include<stdio.h>
#include<string.h>
#include<conio.h>
#include<alloc.h>
void main()
{
char *p[20],temp[20];
clrscr();
int i,j,n;
printf("Enter the nume to be sort\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{ p[i]=(char*)malloc(sizeof(char)*20);
fflush(stdin);
gets(p[i]);
}
prepared by: Shiva pd. Mahato
Dynamic memory allocation:
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(strcmp(*(p+i),*(p+j))>0)
{
strcpy(temp,*(p+i));
strcpy(*(p+i),*(p+j));
strcpy(*(p+j),temp);
}
}
}
printf(" The name in alphabetica order are\n");
for(i=0;i<n;i++)
printf("%s",*(p+i));
getch();
}
prepared by: Shiva pd. Mahato