Unit9 Pointers
Unit9 Pointers
UNIT 9
POINTERS
1. Introduction
Pointer is a variable or data structure that contains the memory address or location of another variable. Variables
contain the values and pointer variables contain the address of variables that has the value. The normal variable
directly accesses their own values whereas a pointer provides indirectly access the values of the variable whose
address it stores. Referencing a value through a pointer is called indirection or dereference.The asterisk (*) operator,
also known as unary or indirection operator, is used before the pointer variable name and it operates only on the
pointer variable.
2. Advantages of Pointer
The pointer enables us to access a variable that is defined outside the function.
It reduces the length and complexity of a program.
It allows passing variables arrays, functions, strings and structures as function arguments.
It supports dynamic memory allocations and de-allocation.
Pointer can return more than one value.
With the help of pointers, variables can be supported without physically moving them.
It increases the execution speed and hence improves the efficiency.
Every pointer contains garbage values before assignment of some valid address. The uninitialized
pointer is called the bad pointer. Pointer variables should be initialized to 0, null or an address. No other constant can
be initialized to a pointer variable. Pointer variable of a particular data type can hold only the address of the variable
of same data type.
4. Pointer operator
C provides two operators for pointer implementation, which are inverse of each other. They are:
4.1 * (Asterisk) operator
It is also called indirection or de-referencing operator. It represents value at address.It returns the value of the
variable to which its operand points.
Syntax: data_type*pointer_variable_name;
Example: int *myptr;
5. Pointer assignment
A pointer is a variable data type and hence the general rule to assign value to the pointer is same as that of any other
variable data type. For example:
Lecture Notes PRITHVI RAJ PANERU
int x, y;
int *ptr1,*ptr2;
Operation Description
ptr1=&x; The memory address of variables x is assigned to the pointer variable ptr1.
y=*ptr1; The contents of the pointer variables is assigned to the variable y (i.e. value of
x), not the memory address
ptr2=ptr1; Address of ptr1 is assigned to the ptr2.
Representation Description
int *p The pointer variable p is integer type pointer. In other word, p is capableto hold the value of
integer type variable.
int *p[10] p is a 10-element array of pointers to integer quantities.
int (*p)[10] p is a pointer to an array of 10 integers. The parenthesis ( ) is necessaryhere, otherwise pwill
be an array of 10 integer pointers.
int (*p) (void) p is a function that return a pointer to an integer quality.
int *p (char *a) p is a function that accept an argument which is a pointer to a character and returns a pointer
to an integer quality.
Examples showing the use of pointer:
Example1:
#include <stdio.h>
#include <conio.h>
void main()
{
int x=10;
int *ptr;
ptr=&x;
printf("\n Address of x = %u", &x);
printf("\n Address of x =%u",ptr);
printf("\n Address of ptr = %u", &ptr);
printf("\n Value of x = %d", x);
printf("\n Value of x = %d", *ptr);
printf("\n Value of ptr = %u", ptr);
getch();
clrscr();
}
Output:
Address of x = 2686684
Address of x = 2686684
Address of ptr = 2686680
Value of x = 10
Value of x = 10
Value of ptr = 2686684
Example2:
WAP to assign a character variable to the pointer and to display the contents of the pointer.
#include<stdio.h>
#include <conio.h>
void main()
{
char x,y;
char *ptr;
x='c'; /*assignment of character*/
Lecture Notes PRITHVI RAJ PANERU
ptr=&x;
y=*ptr;
printf("Value of x = %c",x);
printf("\nPointer value ptr = %c",y);
getch();
clrscr();
}
Output:
Value of x = c
Pointer value ptr = c
6. Types of pointers
6.1 Void pointer
A pointer that points any data type (int or float or char or double) is called the void pointer. Using void pointer the
pointed data cannot be referenced directly. Type casting or assignment must be used to change the void pointer to a
concrete data type to which we can refer.
For example:
#include <stdio.h>
#include <conio.h>
void main ()
{
int a = 10;
double b = 4.5;
void *ptr;
ptr = &a;
printf ("a = %d", *((int *)ptr));
ptr = &b;
printf ("\nb = %lf", *((double *)ptr));
getch();
clrscr();
}
Output:
a = 10
b = 4.500000
7. Pointer Arithmetic
As a pointer holds the memory address of variable, some arithmetic operations can be performed with pointers. C and
C++ support four arithmetic operators that can be used with pointers, such as:
Pointer arithmetic Symbol
Addition +
Subtraction -
Increment ++
Decrement --
Pointer is variables that hold that memory address of another variable. They are not integers, but they can be displayed
as unsigned integers. According to data type declared to the pointer variable,if arithmetic operation is done thenvalues
(contents) will be incremented or decremented as per the data type chosen.
Let p = &a[0] = 1001 i.e. Base address of an array
int type pointer
(2-byte space)
p++ = p+1 = 1001 + 2 = 1003i.e. Address of next element
p = p+5 = 1001 + 10 = 1011 i.e. Address of 5th integer type element.
Example-4:
Lecture Notes PRITHVI RAJ PANERU
#include <stdio.h>
#include <conio.h>
void main()
{
int x,y,*x_pointer,temp;
temp=3;
x=5*(temp+5);
x_pointer=&temp;
y=6*(*x_pointer+5);
printf("x=%d",x);
printf("\ny=%d",y);
getch();
clrscr();
}
Output:
x =40
y =48
Call by value
#include <stdio.h>
#include <conio.h>
void swap (int, int);
void main()
{
int x=100,y=20;
printf("Values before swap\n");
printf("x=%d y=%d",x,y);
swap(x, y);
getch();
clrscr();
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("\nValues after swap\n");
printf("x=%d y=%d",a,b);
}
Call by Reference
#include <stdio.h>
#include <conio.h>
void swap (int *x, int *y);
void main()
{
Lecture Notes PRITHVI RAJ PANERU
int x=100,y=20;
printf("Values beforeswap\n");
printf("x=%d y=%d",x,y);
swap(&x,&y);
printf("\nValuesafterswap\n");
printf("x=%d y=%d",x,y);
getch();
clrscr();
}
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
Output of both:
Values before swap
x=100 y=20
Values after swap
x=20 y=100
In CALL BY VALUE method, the calledfunction creates its own copies of theoriginal values sent to it. Any
changes, thatare made, occur on the called function's copy of values and are not reflected back to the calling function.
In CALL BY REFERENCE method, thecalled function accesses and works with theoriginal values using their
references. Anychanges, that occur, take place on the originalvalues and are reflected back to the callingcode.
For example:
#include <stdio.h>
#include <conio.h>
void fun (int radious, float *area, float *perimeter);
void main()
{
int radious;
float area, perimeter;
printf("Enter radious of circle:");
scanf ("%d", &radious);
fun(radious, &area,&perimeter);
printf("\nArea = %f", area);
printf("\nPerimeter=%f",perimeter);
getch();
clrscr();
}
void fun(int r, float *a, float *p)
{
*a=3.14*r*r;
*p=2*3.14*r;
Lecture Notes PRITHVI RAJ PANERU
}
Example-2: A program to access the array element and particular memory location usingpointer.
#include <stdio.h>
#include <conio.h>
void main()
{
int x[5]={10,20,30,40,50}, i, *p;
p = &x[0];
for(i=0;i<5;i++)
{
printf("\nArray element = %d\t and Memory location = %u", *p, p);
p = p+1;
}
getch();
clrscr();
}
Example 3:
Lecture Notes PRITHVI RAJ PANERU
#include <stdio.h>
#include <conio.h>
void main( )
{
int num[ ] = { 1, 2, 3, 4, 5} ; int i ;
for ( i = 0 ; i <= 4 ; i++ )
{
printf ( "\naddress = %u ", &num[i] ) ;
printf ("element = %d %d %d ", num[i], *(num+i), *(i+num)) ;
}
getch();
clrscr();
}
Output:
Address = 65512 Element = 1 1 1
Address = 65514 Element = 2 2 2
Address = 65516 Element = 3 3 3
Address = 65518 Element = 4 4 4
Address = 65520 Element = 5 5 5
Example 4: WAP to display the contents of 2-Dimensional array using pointer arithmetic.
#include <stdio.h>
#include <conio.h>
void main()
{
int a[2][3]={ {11,12,13}, {14,15,16} },i,j,n,temp;
printf("Contents of the array\n");
for(i=0;i<=1;i++)
{
for(j=0;j<=2;j++)
{
temp=*(*(a+i)+j); //*(*(a+i)+j) = a[i][j]
printf("%d\t",temp);
}
printf(“\n”);
}
getch();
clrscr();
}
Output:
Array[0] = 20
Array[1] = 24
Array[2] = 28
Array[3] = 32
Array[4] = 36
Syntax:
pointervariable= (cast-type *)malloc(size_in_bytes);
OR
pointervariable= (cast-type *) malloc (number of elements * size of each element in bytes);
This function returns a pointer to the allocated memory, or NULL if the request fails.
Example: Write a program to dynamically allocate memory for the array elements using malloc() function
and read and display the array elements
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
void main()
{
int i, n;
int *a;
printf("Number of elements to be entered:");
scanf("%d",&n);
a = (int*)malloc(n*sizeof(int)); //a=(int *)malloc(n*2);since size of “int” is 2 bytes
printf("\nEnter %d numbers:\n",n);
for( i=0 ; i < n ; i++ )
{
scanf("%d",&a[i]);
}
printf("The numbers entered are: ");
for( i=0 ; i < n ; i++ )
{
printf("%d ",a[i]);
}
getch();
clrscr();
}
Output
Number of elements to be entered:4
Enter 4 numbers:
25
13
14
21
The numbers entered are: 25 13 14 21
11.2 calloc()
Lecture Notes PRITHVI RAJ PANERU
The term calloc stands forcontiguousallocation. It is similar to malloc but difference that it initializes zero. It
allocates memory which may/may not be contiguous. It takes two argument (calloc(no.of.var, size of each var)
and allocate block of memory. The calloc will not fail if memory can be allocated in non-contiguous blocks when
a single contiguous block cannot be allocated. But we need to free the memory explicitly while variables are
created using calloc.
Syntax:
Pointervariable= (cast-type *)calloc(number_of_blocks, size_of_each_block_in_bytes);
This function returns a pointer to the allocated memory, or NULL if the request fails.
Example:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
int i, n;
int *a;
printf("Number of elements to be entered:");
scanf("%d",&n);
a = (int*)calloc(n, sizeof(int)); //a=(int *)calloc(n,2);since size of “int” is 2 bytes
printf("\nEnter %d numbers:\n",n);
for( i=0 ; i < n ; i++ )
{
scanf("%d",&a[i]);
}
printf("The numbers entered are: ");
for( i=0 ; i < n ; i++ )
{
printf("%d ",a[i]);
}
getch();
clrscr();
}
Output:
Number of elements to be entered:3
Enter 3 numbers:
22
55
14
The numbers entered are: 22 55 14
11.3 free ()
This build in function frees previously allocated space by calloc(), malloc() or realloc() functions. The memory
dynamically allocated is not returned to the system until the programmer returns the memory explicitly. This can be
done using free() function. Thus, the free() function is used to release the space when it is not required.
Syntax:
free(ptr); where, ptr be any pointer to a memory block created already.
Lecture Notes PRITHVI RAJ PANERU
11.4 realloc ()
This function is used to modify the size of previously allocated space. Sometimes, the previously allocated
space is not sufficient; we need additional space and sometimes the allocated memory is much larger than
necessary. In both situations, we can change the memory size already allocated with the help of function realloc ().
Syntax:
ptr = malloc (size); //Original allocation of memory
ptr = realloc (ptr, newsize); //Reallocation of space