Chapter05(g)
Chapter05(g)
POINTERS
Objectives:
Declare Pointer & Pointer arithmetic.
Pointer to Arrays, string & Object.
“this” pointer concept.
5.1 Concepts of Pointer: Pointer declaration, Pointer operator, address operator, Pointer arithmetic.
5.2 Pointer to Array: Searching, Insertion, deletion
5.3 Pointer to String: Searching, finding length, comparisons, concatenation, reverse
5.4 Pointer to Object: Pointer to Object, this pointer, Pointer to derived class.
5.1 Concepts of Pointer: Pointer declaration, Pointer operator, address operator, Pointer arithmetic.
“A pointer is a variable that holds an address of another variable.”
Consider the following figure.
a
Location name
3 Value at location
6485 Addres of location
We can print the address of variable a by using & operator ( address operator)
void main()
{
int a =3;
cout << “ address of a is : “ << &a ;
}
OUTPUT
Address of a is 6485
DECLARING AND INITIALIZING POINTER VARIABLE:
Ques : How to initialize a pointer explain with a suitable example.(May – 2003)
Pointer is a variable, which stores an address of another variable.
Pointer must be declared with its proper type and its name is preceded by *.
Syntax for declaring pointer: Datatype * variable-name;
Example : int * ptr;
Where ptr is a pointer which can be used to store the address of an integer.
Data type of pointer must be same that of the data type of a variable whose address it is going to store.
After declaring a pointer variable, it must be initialized with the address of another variable.
To initialize a pointer variable use following syntax: Pointer-variable = & ordinary-variable;
Example : int *ptr; // ptr is a pointer
int a = 10; // a is ordinary variable holding an integer
ptr = & a; //initializing pointer with the address of a
ACCESSING VALUE OF A VARIABLE USING POINTER:
To access the value of a variable using pointer, we use * in the expression.
Consider the following example where a is a variable of type int that holds value 10 and p is a pointer that stores
the address of variable a. In short pointer p a points to variable a;
int a =10;
int *p;
p =&a;
We can print the value of variable a using pointer using following expression.
cout << *p;
POINTER OPERATORS:
There are two special pointer operators,
1) & is called address of operator :
This returns the address of(its operand.) a variable. Where address is the internal computer’s memory location of
variable.
cout << &a ; //prints address of variable a
2) * operator which is called “ value at address “ operator.
The “*” is the indirection operator and it is the complement of &. It is the unary operator that returns the
value of the variable located at the address specified by its operand.
SAMPLE PROGRAM :
CHAPTER 5
# include <iostream.h>
void main()
{
int a = 3; // ordinary variable
int *p; // pointer variable
p = & a; // p stores the address of a
cout << “Adress of a = “ << &a << endl;
cout << “ Address of a = “ << p <<endl;
cout << “Value of a = “<< a <<endl;
cout << “value of a = “ << *p <<endl;
}
OUTPUT
Address of a = 1003
Address o a = 1003
Value of a = 3
Value of a =3
POINTER TO POINTER:
A pointer can store the address of another pointer. In other words a pointer can point to another pointer.
a P q
10 1002 4000
1002 4000
In the above example pointer p points to variable a and pointer q points to pointer p.
int a = 10;
int * p; // pointer to ordinary variable
int **q; // pointer to pointer
p = & a; // p points to a
q = &p ; // q points to p.
cout << a ; // prints value of a - 10
cout << *p; //*1002=10 // prints value of a using pointer p- 10
cout << **q ; // **4000= *1002=10 //prints value of a using pointer q - 10
cout << &a; // prints address of a -1002
cout << p; //prints contents of p -1002
cout << q; // prints contents of q - 4000
cout << *q ; // prints value of p using pointer q - 1002
Here a is a variable of type int and p is pointer to variable a and q is pointer to p.
If we want to access value of variable a using pointer ,p then use the following expression, *p ;
If we want to access value of variable a using pointer q , then use the following expression, **q ;
POINTER ARITHMETIC:
The following operation can be performed on a pointer.
1) Addition of a number to a pointer.
int a =7;
int * p = & a;
p = p+2;
2) Subtrcation of a number from a pointer
int a =7;
int * p = & a;
p = p - 2;
3)Subtraction of two pointers.
int a [4] = { 1,2,3,4};
int * p = & a [0]; // p points to the first element of array
int *q = & a [3]; // q points to the last element of array
cout << q –p;
Do not attempt the following operations on pointer.
1) Addition of two pointers.
2) Multiplying a pointer with a number.
3) Dividing a pointer by a number.
CHAPTER 5
Advantages of pointers
- Can return more than one value from function.
-Increasing the programming performance, using pointers we can access the variables faster.
-In case of arrays, we can decide the size of the array at runtime by allocating the necessary space Or
dynamic memory management
-Data structure handling (Linked list, Stack, queue)
p 10 20 30 40 50
10 20 30 40 50
}
Enter string : education
Enter character u want to search : c
Character found at position : 4
Program: To find whether the string is palindrome using pointer to string.
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[20],str1[20],*ptr,*ptr1;
int t=0;
clrscr();
cout<<"\n Enter a string : ";
cin>>str;
strcpy(str1,str);
strrev(str);
ptr=str1;
ptr1=str;
while(*ptr!='\0' && *ptr1 !='\0')
{
if(*ptr!=*ptr1)
{
t=1;
break;
}
ptr++;
ptr1++;
}
if(t==0)
cout << "\nString is palindrome.";
else
cout << "\nString is not palindrome.";
getch();
}
POINTER TO OBJECT:
A pointer can point to an object created by a class.
Consider the following example :product x;
Where ‘product’ is a class and x is an object of product class.
We can define pointer ptr of type product, as shown below. product *ptr.
Now this ptr can be used to store an address of object of class product. Pointer to objects are useful in creating objects
at run time.
Example:
Class product
{
private: int code;float price;
public:void getdata(void)
{
CHAPTER 5
cout << “enter code”;
cin>>code;
cout << “enter price”;
cin>>price;
}
void display(void)
{
cout << code <<price;
}
};
void main()
{
product p1; // create object of product
product *ptr; // create pointer of type product
ptr = &p1; // ptr points to object p1
p1.getdata (); // Invoking getdata() using object
ptr -> getdata (); // Invoking getdata() using pointer to obejct
p1.display();
ptr ->display();
}
Here -> is called member access operator.
It requires a pointer to object on LHS and member function on RHS.
NOTE : The following statements are same
1) p -> getadat();
2) (*p) . getdata();
CREATING OBJECTS USING POINTER / NEW OPERATOR
We can create the object using new operator. The new operator is used to create an object at run time.
Syntax :
Datatype *pointer-var = new datatype;
Example :
product *p = new product;
The new operator allocates required memory space for the object and returns the address of the allocated memory to
the pointer variable on LHS ( i.e. p)
We can also create an array of objects using pointer.
Syntax :
Datatype *pointer-var = new datatype [ size];
product *p = new product [5];
This statement allocates memory space array of 5 objects of type product and return the base address of the array to
the pointer p;
Using new operator we can create an array of integers also.
Thus to create an array of 10 integers write,
int *p = new int [10];
PROGRAM ILLUSTRATING USE OF POINTER TO OBJECT:
# include <iostream.h>
class product
{ int code;
float price;
public:void getdata(void)
{
cout << “enter code”;
cin>>code;
cout << “enter price”;
cin>>price;
}
void display(void)
{
cout << code <<price;
}
};
void main()
{ int n;
CHAPTER 5
cout <<”enter how many products “ ;
cin >> n;
product *p = new product[n ]; // create array of 5 products using pointer to object.
for (int I=0; I<=n ; I++)
{
p -> getdata ();
p-> display();
p++;
}
}
This Pointer :
Ques : Explain the concept of this pointer (Dec-2003 ,may-2005)
C++ uses a unique keyword called ‘this’ to represent an object that invokes a member function.
This unique pointer is automatically passed to a member function when it is invoked.
‘this’ is a pointer that always points to the object for which the member function was called.
For example, the function call A.max() will set the pointer ’this’ to the address of the object A. Next time suppose
we call B.max() , the pointer ‘this ‘ will store address of object B.
Consider the following example:
class sample
{ int a;
public :void setdata (int x)
{ this -> a = x;
}
};
The private variable a can be directly used inside a member function like a =123;
We can also use the following statement to access private variable a this -> a =123;
class example
{ private : int m;
public:void setdata( int a)
{ m = a ; // one way to set data
this -> m = a; // another way to set data using this pointer
}
void showdata (void)
{ cout << m; // one way to display data
cout << this ->m; // another way to display data using this pointer
}
};
Practical use of this pointer:
1) this pointer is normally used when we overload the operator using member function
2) this pointer is used to return object by reference.
We can pass object to the function and return object from the function either by value or by reference. When
entire object is passed / returned by value, a copy of that object is created. This leads to considerable wastage of
memory.
But when the object is passed/ returned by reference, no new copy is created, only reference to that object is
passed to the function, this saves memory.
We can return object by reference using this pointer as shown below.
Return *this;
The above statement returns the object by reference.
# incluide <iostream.h>
Class base
{ public:
CHAPTER 5
void display ()
{ cout << “In base class “<< endl;
}
};