Pointers
Q:
Page 2 of 24
All of the above variables that we have declared are termed as simple
programming variables (You learned about them in Class XI) .
The concept of pointer is not new in C++ , it has been there in right from the
generation of Language C. Language C is considered as one of the most
efficient middle level programming language, because of its ability to write codes
for hardware devices, like CPU , Disk Drives, Keyboards etc. One of the facility in
C which provided it these capabilities was the presence of Pointers with it.
Following are some of the application area domains where a Pointer concept
could be applied:
a)
b)
c)
d)
Pointer Definition :
A pointer is a variable which stores the memory address of another
variable of same data type.
Let us try to explore this definition with a particular example :
int a = 32 ;
When the above line is being executed by the compiler, it will allocate the
variable a with a random hexadecimal address say : 0x8fbffff4. This memory
address will remain attached with the variable a till the variable is present in the
program scope.
Try to Do :
Copy the above hexadecimal memory addresses and convert it using calculator to its decimal form.
Write the decimal equivalent in your notebook.
The above scenario could be represented pictorially as :
variable a
32
Prepared By Nishant Tiwari, PGT Computer Science
Page 3 of 24
a memory space of 2 bytes with a
value equal to 32
0x8fbffff4
For sake of simplicity from now onwards we would take decimal values as
variable addresses instead of taking hexadecimal addresses.
We are observing that the addresses allocated to simple variables are themselves
a type of values ( i,e hexadecimal values). So a question arises that cant
address values be stored again in some variables? If yes, then what would be the
data type of those variables? Whether those variables would be like simple
variables or different from it? What would be the size of those variables?
Let us try to sort out the answers of all of the above questions.
Since a variable which is storing an address of another variable, must be a
special one, so in C++ these variables are treated specially and are declared
using special syntaxes.
Pointer Declaration:
A pointer declaration is similar to the declaration of a simple programming
variable except that it is declared with a (*) asterisk symbol. The syntax is as
follows :
For eg.
Note : The pointer variable name obeys all the rules and regulations which a normal variable
naming follows. Pointer also have some data types.
Pointer Initialization:
We know that a simple variable is initialized with a value using assignment
operator ( = ) like :
int a = 20 ; // a simple variable initialized by a value equal to 20
Prepared By Nishant Tiwari, PGT Computer Science
Page 4 of 24
Likewise whenever we declare a pointer variable we must initialize it with a
particular value using the same assignment operator (=). But as we know from
earlier definition of pointers that a pointer variable only holds an address of
another variable, so the value assigned to a pointer must be an address of
another simple variable of same data type.
// Line No. 1
// Line No. 2
The Line No. 1 of the above code snippet creates an ordinary variable a having
an integer value equal to 20.
The Line No. 2 of the above code snippet creates a Pointer variable ptr having a
value assigned to it. We observe that the value assigned to it is the address of
a ( i,e. &a). So from the above code it is inferred that a pointer variable (ptr)
must be initialized with address of a simple variable (a).
int a
20
0x8fbffff4
an integer variable a
the value 20
&a ( address of a )
int *ptr
0x8fbffff4
Try to initialize a pointer variable with an address whenever you create one
Very Imp. Note :
such. If you are not initializing it will point no where or to some garbage address , that would result
Prepared
By Nishant
Tiwari,
PGTwith
Computer
Science
into unpredictable program results. We
can initialize
a pointer
variable
a NULL
(/0) value.
Page 5 of 24
c. Execute the following code (include the required header files of your
own) and observe the output :
main( )
{
int a = 35 ;
cout<< a;
int *p = &a ;
cout<< p;
getch();
}
d. A pointer variable is also a variable so it will also occupy memory space.
Since it occupies a memory space it must be also having some fixed
memory address. If this memory address has to be stored then what
type of variables we would need? Whether it would be a normal
variable, a pointer variable or something else? Explain.
i)
Page 6 of 24
When we declare the pointer variable we are in habit to write :
int * p ; [ here the * only indicates that p is a pointer variable]
ii)
cout<< *p
int a
int *p
20
0x8fbffff4
0x8fbffff4
address of a ( &a or p
itself)
value at p (a or *p )
Execute the following and see which of the two lines are giving
same output:
main( )
Prepared By Nishant Tiwari, PGT Computer Science
Page 7 of 24
{
int a , *ptr ;
a = 30 ;
ptr = &a;
cout<<a << \n;
cout<<&a << \n;
cout<<*ptr<<\n;
cout<<ptr<<\n;
getch( );
}
Page 8 of 24
be well defined during the run time of the program, not during the design time
itself, as is done in the case of the example given above.
C++ provides us with a NEW operator to create fixed size array with a size
defined during run time. This whole block is treated to be a static block of
memory but created in a more dynamic way, asking the size of the array to be
inputted from the user.
Lets understand the concept by running the following code snippet:
main()
{
int *MyArray;
// Line 1 :
int size ;
cout<< Define the size of the array you want to create;
cin>> size;
// Line 4
Where,
MyArray = a pointer which holds the address of the first member of
the array created at R.H.S using new operator.
Prepared By Nishant Tiwari, PGT Computer Science
new
int
size
Page 9 of 24
= Keyword to allocate memory chunks during run-time.
= required data-type of the array member. This data-type
can be also float , char , void etc.
= the required amount of memory chunk, defined by the
user at design time or run time
const Pointers :
We can create a ordinary const variable by using following syntax :
const <data-type> <var_name> = <value>;
Eg.
One of the most important characteristics of a const variable is that, once they
have been assigned with some values, that value could not be changed at any
point of time throughout the whole program.
Prepared By Nishant Tiwari, PGT Computer Science
Page 10 of 24
For example in the above statement MyVar is a const variable and its value could
be reinitialized or changed again i,e we cant write following statement after we
have declared MyVar as const :
Or
MyVar = 23;
MyVar ++ ;
// Invalid
// Invalid
Likewise we can have out pointer variables also as const pointer variables by
using the same syntax as above with a slight modification, such as :
const int * MyConstPointer = &<some variable>;
More precisely :
int a = 20 , b = 30 ;
const int * MyConstPointer = &a;
After we have declared a const pointer, we cant change its address any how, at
any point of time in a program. So writing the following codes would cause
errors:
int a = 20 , b = 30 ;
const int * MyConstPointer = &a;
MyCostPointer = &b;
// Error ! cant assign a second value to a const
pointer since it has already been initialized with
the value i,e address of variable a.
Pointer Arithmetic :
Lab Activity
Part a)
:
Execute the following code and note the two output lines obtained.
main( )
{
clrscr();
int a = 20 ;
int * p = &a;
cout<< p ;
p++;
cout<< p;
getch( );
}
Prepared By Nishant Tiwari, PGT Computer Science
Page 11 of 24
Part b)
Execute the following code and note the two output lines obtained.
main( )
{
clrscr();
float a = 20 ;
float * p = &a;
cout<< p ;
p++;
cout<< p;
getch( );
}
Part c)
Part d)
Subtract the first output from the second output in each case i,e
part a) and part b). Observe the two results (decimal values)
obtained. Is it coming 2 and 4? Why? What idea you get from it?
As we can add or subtract integers from a normal variable, likewise we can also
add and subtract integers from pointer variables. So all of the following
statements are very correct:
int a = 80 , b = 90 ;
int * MyPointer = &a , * YourPointer = &b;
MyPointer = MyPointer + 1;
YourPointer = YourPointer 2 ;
MyPointer += 5;
- - YourPointer ;
What happens when we increment / decrement a pointer variable by a
certain value ?
Note :
Never try to apply multiplication, division or modular division operator on Pointers. Pointer
arithmetic does not allow these operations. So the statements like:
int var = 30 ; int *ptr = &var ; ptr /= 2 ; ptr % = 4
are invalid operations.
What would be the output of the following code snippet and why?
Prepared By Nishant Tiwari, PGT Computer Science
Page 12 of 24
main ( )
{
const int * ptr ;
int a = 80 ;
ptr = &a ;
a += 3;
cout<< a;
ptr++;
cout<<ptr;
}
memory
addresses
8 fc4fff4
8 fc4fff6
8 fc4fff8
8fc4fffa
8fc4fffc
ptr
If you observe the whole scenario you will find that directly or indirectly we are
getting an array containing 5 members, each of these members having a integer
values (int data-type). The base addresses being assigned to the pointer variable
ptr itself.
Now we are free to apply the pointer arithmetic to the base pointer ptr to read
and write other locations as well.
The
The
The
The
The
Page 13 of 24
Similarly to read and write value at these locations we can readily use (*)
operator i,e.
*p tr i.e. *(ptr +0)
*( ptr + 1)
reads
*( ptr + 2)
reads
*( ptr + 3)
reads
*( ptr + 4)
reads
/
/
/
/
reads/writes
writes value
writes value
writes value
writes value
Now lets think the whole process in reverse order. Thinking in reverse manner
you find that we have ultimately created a 1-Dimensional Array having 5
elements in it.
Let us proof this by comparing the following two programs :
main ( )
{
int arr[5] ;
for(int i = 0 ; i<=4 ; i++)
{
cout<< Input ;
cin>>arr[i];
}
}
main( )
{
int *ptr = new int[5];
for(int i = 0 ; i <= 4 ; i++)
{
cout<< Input;
cin>> *(arr + i) ;
}
}
Both of the above versions of the programs are equivalent. Thus we can infer
that the name of base pointer (ptr) in the second version is acting same as the
name of the array (arr) itself present in the second version.
Note : The name of any array declared in any C++ program, is a pointer to the address of the
first element of that array.
The above two versions can be used in compliment of each other, as and when
required. They can also be used in mixed form. So the following expressions are
equivalent :
arr[i]
* (arr +i)
So , following mixed expressions can be used while writing codes using arrays :
main( )
{
int MyArray[5] ;
Prepared By Nishant Tiwari, PGT Computer Science
Page 14 of 24
//Inputting array elements
for(int i = 0 ; i <= 4 ;i++)
{
cout<< Input Values : ;
cin>> MyArray[i];
}
Execute the following code and note down the error if obtained
otherwise note down the output
main( )
{
clrscr();
int arr[5] = {12 , 14 , 16 , 18} ;
for(int i = 0 ; i <= 4 ; i++)
{
cout<< arr[i];
arr++;
}
getch( );
} // end of main( )
Part b)
Execute the following code and note down the error if obtained
otherwise note the output
main( )
{
clrscr( );
int *arr = new int[5];
for(int i = 0 ; i <= 4 ; i++)
{
cout<< Enter a value : ;
Prepared By Nishant Tiwari, PGT Computer Science
Page 15 of 24
cin>> *(arr + i) ;
}
for(i = 0 ; i <= 4 ; i++)
{
cout<< *arr;
arr++;
}
getch();
}
Part c)
Part d)
Now execute the following code and note down the error or
output whatever you get:
main( )
{
clrscr( );
const int *arr = new int[5];
for(int i = 0 ; i <= 4 ; i++)
{
cout<< Enter a value : ;
cin>> *(arr + i) ;
}
for(i = 0 ; i <= 4 ; i++)
{
cout<< *arr;
arr++;
}
getch();
}
Part e)
By performing the activity given above you would find that all arrays declared in C++ are nothing
but a const pointer having the address of the first element of the same array.
Page 16 of 24
Pointer with different operators :
Pointer with Assignment operator :
We know that we can assign value of a simple variable into another variable by
using assignment operator ( = ) for e.g.
int a = 90 , b = 80 ;
b=a;
When we write pointer a = b then the address which is being stored in b i,e a
Hexadecimal value , gets copied into pointer a removing any of its previous
contents (address).
Pointer with comparison operator ( ==)
Just like we use comparison operator (==) between two simple variables, we can
also use it between two pointer variables.
Page 17 of 24
Now try to predict the output of the following code:
main( )
{
int a = 30 , b = 30 ;
int *p = &a ;
int *q = &b ;
if ( p == q)
cout << Kamal, Are you joking !;
else
cout<< Pointer is so easy following this study material;
}
If you are not able to find the answer yourself, execute the code and discuss with
your teacher.
Note : Similarly we can also use != between two pointer variables.
Sometimes we also compare a pointer variable with NULL or \0 to check whether it is
pointing No where.
Pointers and Strings:
We already know that a string is not just a 1-dimensional array of characters but
it is 1 dimensional array of characters which is terminated by a Null (\0)
character. This can be well defined in terms of following diagram :
char MyName [30] = Kamal;
K
\0
Memory addresses
8fc4fff4
8fc4fff5
8 fc4fff6
a
8 fc4fff7
l
8fc4fff8
\0
8 fc4fff9
Page 18 of 24
Now keeping the above figure in mind fill in the following blanks :
a)
MyName + 2
____________
b)
*(MyName +1)
____________
c)
*(MyName + strlen(MyName) ) =
_____________
Conclusions :
i)
We know that a string is terminated by a null character.
ii)
A string name is a pointer to the first character i,e name of the string is
holding the base address of the string.
By analyzing i) and ii) above we find that now there is no need to declare a string
like char str[30]; (as we have done in class XI). This can be more dynamically
declared as char *str (The benefit here is that we dont have to fix the size).
Only declaring a character pointer is sufficient to hold an entire string, since the
end point of the string will be automatically marked by NULL (\0) character,
during run time.
Hence:
char str[30]
or more dynamically as ,
char *str;
Whatever string you assign to this it will accommodate, since the only need is to
mark the beginning and end memory locations of the string.
Prepared By Nishant Tiwari, PGT Computer Science
Page 19 of 24
Try to find the error or output:
#include<string.h>
main( )
{
char * MyName = Kamal Kant Gupta;
int i = 0;
while( I <= strlen(MyName) -1 )
{
cout<< *(MyName + i)<<\n\t;
}
getch( );
}
Q:
Observe the following two codes and then put your views about one of
them which you feel is better implementation than the other. (Both the
implementations solves a same problem). Give reasons.
main( )
{
char *book = The Alchemist;
while( *book != \0)
{
cout<< *book ;
book++;
}
}
main( )
{
char *book = The Alchemist;
int i = 0 ;
while( *(book+i) != \0)
{
cout<< *(book+i) ;
i++;
}
}
Pointer to a Pointer:
So far we have understood that a pointer is also a special variable, which is
having a special role to play. One question that might strike in your head that if a
pointer is a variable it must also have some memory allocation with a specific
memory address (Hexadecimal address). Yes you are perfectly right. Pointers do
have their own addresses just like a simple variable.
Page 20 of 24
Now a million dollar question arises that if pointers do have their own memory
addresses, then their might be some variable which must be having ability to
store memory address of a pointer.
Yes there are special variables which are intended to store the memory
addresses of other pointer variables. These special variables are called pointer
to a pointer or more precisely Double Pointers. The whole scenario could be
explained by following diagram:
int a
Ordinary Variable
value of a
56
address of a
8fc4fff2
int * aa
8 fc4fff2
value of aa
address of pointer aa
9acfff4
int ** aaa
9acfff4
Pointer to
a pointer
variable
=Note
: A double pointer is always being assigned the address of another pointer variable , or the
value of another double pointer variable. If we try to assign the a value of simple pointer
variable into a Double pointer it will cause error. E.g. :
int a = 90 , b = 46 ;
int *p = &a ;
int * q = &b;
Prepared
By Nishant
Computer
Science
int ** r = p; // Invalid assignment
cant assign
simpleTiwari,
pointer PGT
to a double
pointer
int **s = &p;
int **f = s
// Correct can assign double pointer to another double pointer.
Page 21 of 24
Array of Pointers :
In class you have implemented 2-D arrays as follows :
int TwoDArray[3][3]; // a 2 D integer array of order 3 x 3
0x4cff
f2
*(str +1)
0x4cff
f9
\0
0x4cfff2
*(str +2)
* (str + 3)
:
:
0x4cfff9
:
:
\0
Page 22 of 24
Yes of course this can be done, just like you have captured the address of first
character of a string into a char pointer, to grab the whole string, you can also
use a double pointer to capture the address of first pointer variable of that Array
of pointers.
So to hold an Array of strings one can use a double pointer using following code
snippet:
char CityName = {
Delhi,
Kolkata,
Mumbai,
Chennai
};
or
char ** CityName = {
Delhi,
Kolkata,
Mumbai,
Chennai
};
Exercise : Try to write a program which will read and write array of strings from user using the above
double pointer notation.
Page 23 of 24
//function IncreaseByTen
void IncreaseByTen(int *ptr )
{
*p tr += 10;
}
Predict the output of the above code.
The output of the above code snippet would be 70 and 80. This is because
we have called the function IncreaseByTen( ) by passing the address of the
variable x as an actual parameter. This address is being copied into the
formal parameter ptr of the function, which is a pointer variable. Since this
variable holds the address of the x so any changes made at this address
( by statement : *ptr+=10 ) would made changes on the value stored at
that address i.e. on the value of x.
Similarly we can have more than one pointer variables as formal parameters to a
function separated by comma.
Now if you want to point a pointer to these two variables P1 and P2, then
we have to declare the pointer variables like :
Point *f = &P1;
Point *l = &P2;
One big question arises that how can we access the data members of a structure
variable using these pointer variables?
Page 24 of 24
For this we make use of direction operator ( ). For example if we want to print
the value of the X- Coordinate and Y-Coordinate of structure variable P1 making
use of its pointer f then we must write the statement as :
cout<< f
XCoord << f
YCoord ;
Remember : You access the data members of a structure variable using structure variable by using
component operator ( . ) i.e. to print XCoord and YCoord of P1 you were writing :
cout<< P1.XCoord << P2.XCoord ;
Whereas if we try to access the data members of a structure variable using pointer to that structure
variable then we make use of the direction operator
cout << P1
XCoord << P1
YCoord;
) to