Вы находитесь на странице: 1из 108

Chapter : 7Pointers

7.1
7.2

7.3

7.4
7.5
7.6
7.7
7.8
7.9
7.10
7.11

7.12
7.13

7.14
7.15
7.16

Introduction
Declaration of Pointers
7.2.1 Reference Operator (&)
7.2.2 Pointer variables
7.2.3 Size of pointers
7.2.4 Dereference Operator (*)
Initialization of Pointers
7.3.1 Null Pointer
7.3.2 Void Pointer
Pointer Arithmetic
Pointers and Arrays
Pointers and Strings
Multidimensional arrays and pointers
Pointers to structures
Pointer to objects
Pointers and constants
Pointers and Function argument
7.11.1 Call by value
7.11.2 Call by reference
7.11.3 Call by pointers
7.11.4 Function returning Pointers
Pointer to Pointers
Dynamic memory allocation/deallocation operators
7.13.1 new operator
7.13.2 delete operator
7.13.3 Pointers and objects
7.13.4 Memory Leaks
This Pointer
Self Referential structures
Reference variables

7.1 Introduction
C++ is a very rich language with so many features .Pointer is one of the powerful
feature of C++. Pointers allows direct dealing with memory addresses and helps in
creating and manipulating dynamic data structures like linked list ,queues and stacks.
Defining pointers and using them to access the variable pointed by them is an important
concept, thoroughly covered in this chapter. The basic pointer concepts, pointers with
other features of C++ like arrays, strings, functions, structures and object variables are
also explained in this chapter.
Advantages of pointers
1. Pointer improve the efficiency of the certain routines by sharing them between
number of entities. It allows different sections of the code to share information
easily
2. Pointers enable complex "linked" data structures like linked lists and binary trees
& graphs
3. It is a way through which memory location of the variables can be directly
manipulated as and when required

7.2 Declaration of Pointers


In earlier chapters ,We have already discussed how variables can be defined in C++.
We can define integer variable , float , character , structure ,or class variable . A variable
in a program is something with a name & the value of which can vary.
consider the following statement :
int
x;
This statement declares a variable x which can take integer values .This statement also
implies that the space of 2 bytes is reserved in the memory for the variable x.
x = 57;
this statement assign the value 57 in the variable x.
All the variables defined are stored in the computers memory . The memory of
computer can be imagined as a succession of memory cells, each one of the minimal size

of one byte. These single-byte memory cells are numbered in a consecutive way, so as,
within any block of memory, every cell has the same number as the previous one ,plus
one.
Every variable defined has unique address in the memory . like consider this diagram :

The variable x has the memory address 1003 and has the value 57. The address of the
variable can be obtained by an address operator & (or also known as reference
operator) . This operator when applied to variables gives the memory address of that
variable. so the following program segment
x = 57;
cout <<Value of x is << x;
cout<< Address of x is <<&x ; will display the following output
Value of x is 57
Adddress of x is 1003 ( as per the diagram)
(please note memory addresses are represented as hexadecimal integers which is dependent on the
compiler and operating system . For the sake of understanding the concept , memory addresses
are taken as simple decimal numbers )

7.2.1

Reference operator (&)

When we declare variable, the amount of memory is defined for that variable
defined and the unique address is assigned to that variable by the compiler during
run time or compile time .
Sometimes ,we want to operate on the address of these variables in order to operate
with relative positions to it.

The address that locates a variable within memory is called as reference to that
variable. This reference to a variable can be obtained by preceding the identifier an
ampersand sign (&), known as reference operator or address operator, and it can be
literally translated as "address of". It is a unary operator which gives the address of
its operand.
The address & operator applies to objects in memory that is variables , array
elements , structure and class objects . It cannot be applied to expressions, constants,
or register variables.
int y=5;
cout << &y;
will display the address of the variable y.

7.2.2

Pointer variables

Assume that there is another variable ptr which holds the address of x means :
int *ptr;
ptr = & x;
this statement assigns the address of x to the variable ptr and
ptr is said to point to x .

Ptr is called as pointer .It does not store simple values .instead of this it store reference
or address to another variable . A pointer holds the address of the very first byte of the
memory location where it is pointing to. the address of the first byte is also known as
base address.

Def
A pointer is a variable which contains the address of another variable.
ptr is a pointer variable which contains the address of some other variable ( of type
integer in this case) . Then obviously a pointer variable is not the same type as integer
variable . then how they are declared like

where ptr is not an integer variable but ptr can hold the address of the integer variable
i.e. it is a pointer to an integer variable ,but the declaration of pointer variable does
not make them point to any location .

int i=57

57

assigning address of i to ptr , ptr = & i; will result in

This is the initialization of the pointer variable. since the pointer can point to any
portion of the memory ,it is a good programming practice to initialize the pointer .
(Arrows shown in the figures are just the logical illustration of the concept otherwise pointer
contains the address of the variable ,which is assigned to it.)
we can also declare the pointer variables of any other data types . For example:
double * dptr;
char * ch;
float * fptr;
These are three declarations of pointers. Each one is intended to point to a different data
type, but in fact all of them are pointers and all of them will occupy the same amount of
space in memory (the size in memory of a pointer depends on the platform where the
code is going to run). Nevertheless, the data to which they point to do not occupy the
same amount of space nor are of the same type: the first one points to an double , the
second one to a char and the last one to a float. Therefore, although these three example
variables are all of them pointers which occupy the same size in memory, they are said
to have different types: int*, char* and float* respectively, depending on the type they
point to.

7.2.3

Size of pointers

The size of a pointer is dependent upon the architecture of the computer a 32-bit
computer uses 32-bit memory addresses consequently, a pointer on a 16-bit machine
is 16 bits (2 bytes). ,on a 32 bit machine , a pointer would be 32 bits i.e. 4 bytes,On a 64bit machine, a pointer would be 64 bits (8 bytes).
Example : 7.1 Showing the size of pointers
#include<iostream.h>
#include<conio.h>

int *iptr;
char *cptr;
float *fptr;
void main()
{
clrscr();
cout<<"size of integer pointer is :"<<sizeof(iptr)<<endl;
cout<<"size of character pointer is :"<<sizeof(cptr)<<endl;
cout<<"size of float pointer is :"<<sizeof(fptr);
}
output
size of integer pointer is : 4
size of character pointer is : 4
size of float pointer is : 4
Note that the size of pointer does not depend upon the data type of the value it is
pointing to.
It can be noticed from this example that , the size of the pointer is always the same. This
is because a pointer is just a memory address, and the number of bits needed to access a
memory address on a given machine is always constant.
Pointers are a very powerful feature of the C++ language that has many uses in
advanced programming. Further ahead, we will see how this type of variable is used
and declared.

7.2.4

Dereference operator (*)

A pointer variable can be used directly to access the value stored in the variable which
it points to. For this, we simply have to precede the pointer's identifier with an asterisk
(*), which acts as indirection or dereference operator and that can be literally translated
to "value pointed by".
Def
The unary operator (*) is the dereferencing pointer or indirection pointer , when
applied to the pointer can access the value the pointer points to.

Therefore, following with the values of the previous example, if we write:


cout << * ptr
This will display the value of the variable i as 57.which is same as
cout<< i ;
hence we can say y and *ptr referring to the same value 57.
To understand the concept more clearly,
let s consider the program segment given below :
int i = 15;
int * ptr;
ptr=&i;

cout << endl<<Value of i is :<<i;


cout << endl<<Address of i is :<<&i;
cout << endl<<Value of i:<< *ptr ;
cout << endl<<Address of i is :<< ptr;
cout << endl<<Address of y is :<<&ptr;
will display the following output :

Vvalue of i is : 15
Address of i is : 1003
Value of i: 15
Address of i is : 1003
Address of y is : 2712
in other words when ptr is assigned with the address of i then :
Ptr is the same as &i
*ptr is the same as i

Now have a look at this code:


Example : 7.2

Showing the use of pointers.

#include <iostream.h>
int main ()
{
int first, second;
int * mypointer;
mypointer = &first;
*mypointer = 10;
mypointer = &second;
*mypointer = 20;
cout << "first value is " << first << endl;
cout << "second value is " << second << endl;
return 0;
}

output
first value is 10
second value is 20
Dereferenced pointer may also be used on the left side of the assignment operator like

*ptr = 10
which makes the value of y as 10.

ptr
10
03

10

It is also used to read in the value of i from the user like


cin>>*ptr;
the value entered by the user is stored in the variable i.

Remember
address operator (&) and dereferencing operator (*) are unary operator which are
evaluated right to left in the expression .

MYNOTES
A variable is declared by giving it a type and a name (e.g. int k;)
A pointer variable is declared by giving it a type and a name (e.g. int *ptr) where
the asterisk tells the compiler that the variable named ptr is a pointer variable and
the type tells the compiler what type the pointer is to point to (integer in this
case).
Once a variable is declared, we can get its address by preceding its name with the
unary & operator, as in &k.
The size of a pointer is dependent upon the architecture of the computer .
The size of the pointer is always the same irrespective of the data type it is pointing to.
We can "dereference" a pointer, i.e. refer to the value of that which it points to, by
using the unary '*' operator as in *ptr.
An "lvalue" of a variable is the value of its address, i.e. where it is stored in

memory. The "rvalue" of a variable is the value stored in that variable (at that
address).
& is the reference operator and can be read as "address of"
* is the dereference operator and can be read as "value pointed by"
A variable referenced with & can be dereferenced with *.

7.3 Initialization of pointers


consider the following snippet :
int x,y,*ptr;
x=57;
y=*ptr;

here ptr is used without being assigned a proper address

y is assigned a value whatever ptr is pointing to .but ptr is not pointing to anywhere ,it
may contain the address of any portion of the memory which is unknown or
uninitialized so, there is a possibility y is assigned a junk value.
Ensure that pointers are assigned and initialized with valid addresses before their usage.
Pointer can be initialized with a 0 or NULL or a valid address
When you declare the pointers it need to explicitly initialized with the valid address
int num;
int * ptr;
ptr= &num;

// pointer is initialized with the address of the integer variable

now the pointer initialization takes place and assigning the pointer reference to the
variable num.
the compiler also allows the special case that we want to initialize the content at which
pointer points to with constants at the same moment the pointer is declared :
char *str = Hello;

In this case, memory space is reserved to contain "hello" and then a pointer to the first
character of this memory block is assigned to str. If we imagine that "hello" is stored at
the memory locations that start at addresses 1003, we can represent the previous
declaration as

7.3.1

The null pointer

Sometimes it is useful to make our pointers initialized to nothing . This is called a null
pointer.
A null pointer is the pointer does not point to any valid reference or memory
address .We assign a pointer a null value by setting it to address 0:
int *iptr;
iptr=0;
or
by using the keyword define in C++ compiler
iptr = NULL:
This statement assign address 0 to iPtr . This statement describe a special preprocessor
define called NULL that evaluates to 0. hence A null pointer is a pointer type which has
a special value that indicate it is not pointing to any valid reference .Even though this is
not technically part of C++, its usage is common enough that it will work in every C++
compiler.

7.3.2

Void Pointer

Every pointer points to a specific data type except a pointer to void which can point
to any data type form double to characters but it cannot be directly dereferenced .It
has a great facility of pointing to any data type. It can only be dereferenced by casting
the address in the void pointer to a concrete data type before dereferencing it . This
conversion of pointer to some other valid data type is achieved by using the concept of
type-casting .It is generally use to pass generic arguments to functions.
void * vptr;
int i;
float f;
double d;
the statements
vptr = &i
vptr = &f
vptr = &d

//declaration of void pointer

//making the pointer vptr point to integer type of variable


//making the pointer vptr point to float type of variable
//making the pointer vptr point to double type of variable

All these statements are valid , as void pointer can point to objects of any data type.
Direct dereferencing of void pointer is not permitted. The void pointer must first be
explicitly cast to another pointer type before it is dereferenced. Also it is not possible to
do pointer arithmetic on a void pointer.

MYNOTES

A pointer which has been declared as a variable can point to any portion of the
memory therefore need to be initialized.

Pointer can be initialized with a 0 or NULL or a valid address

A null pointer is the pointer does not point to any valid reference or memory address .We
assign a pointer a null value by setting it to address 0:

Every pointer points to a specific data type except a pointer to void which can point to any data
type form double to characters

Please note that asterisk sign (*) that we use when declaring a pointer only means that
the variable being declared is a pointer .It is part of its type compound specifier, and it

should not be confused with the dereference operator that we have seen a bit earlier (*).
They are simply two different things represented with the same sign.

7.4 Pointer arithmetic

Hope you must have understood the declaration and initialization of variables . Now we
will see how we can manipulate the pointer variables. Pointer arithmetic operations are
different from normal arithmetic operations.
These operations may be allowed to perform on Pointers:

Add or subtract integers to/from a pointer. The result is a pointer.


Subtract two pointers to the same type. The result is an int.
Multiplying, adding two pointers, etc. don't make sense.

Only two arithmetic operations , addition and subtraction are mostly used operation
on pointers. Both addition and subtraction operation depend upon the size of data type
pointer variable points to.
consider the following pointers :
int x;
int *iptr , * ptr;
char *cptr;
Adding or subtracting integer to / from pointer
Simple addition or subtractions operations can be performed on pointer variables
If *iPtr points to an integer, *iptr + 1 is the address of the next integer in memory after
*iPtr. *iPtr - 1 is the address of the previous integer before *iPtr.
x=57
iptr=&x ;

iptr= iptr + 1 or iptr ++ ;


This is the most common arithmetic operation done using pointers i.e. incrementing the
pointer by 1. The pointer is shifted to next memory location not by one byte but by 2
bytes as iptr type is integer and integer will take internally two bytes of storage.

It is to note that when pointers are incremented by1 the size of the variable to which it is
pointing to ( 1 for char, 2 for int , 4 for float, 8 for double)is taken into account.
Incrementing a pointer will result in the following computation :
new address of pointer = old address of the pointer + scaling factor
where scaling factor is the size of variable it is pointing to.

similarly
iptr= iptr - 1 or iptr -- ;
The pointer is shifted to previous memory location 1003 to 1001 not by one byte but by
2 bytes as iptr base type is integer and integer will take internally two bytes of storage.

Remember : Pointer is always incremented or decremented as per the type of value it is


pointing to .
Note that iPtr+1 does not return the address after iPtr, but the next object of the type that
iPtr points to. If iPtr points to an integer (size is 2 bytes), iPtr+3 means 3 integers after
iPtr, which is 6 addresses after iPtr. If cPtr points to a char, which is always 1 byte,
cPtr+3 means 3 chars after cptr, which is 3 addresses after cPtr.
Example :7.3 find the output of the following if the address of n is 100.
float n=7;
int *ptr=&n;
cout<<ptr << endl;
cout<<ptr+1 << endl;
cout<<ptr +2<< endl;
cout<<ptr+3 << endl;
output:
100
104

108
112
Note that pointer ptr is incremented by 4 bytes at a time as it is pointing to float type of
data.
Example : 7.4 showing pointer arithmetic
char *mychar;
short *myshort;
long *mylong;
and that we know that they
respectively , So we Write
mychar++;
or
myshort++;
or
mylong++;
or

point to memory locations 1000, 2000 and 3000


mychar=mychar+ 1
myshort = mshort + 1
mylong = mylong +1

Example 7.5 find the output of the following


#include<iostream.h>
int one[]={1,2,3};
void main()
{
int *ptr;
ptr=one;
cout<<*ptr<,endl;

ptr++;
cout<<*ptr
}
output
1
2

Both the increase (++) and decrease (--) operators have greater operator precedence than
the dereference operator (*),but it shows different behaviour ,consider the following
expression may lead to confusion:
*p++
Because ++ has greater precedence than *, this expression is equivalent to *(p++).
Therefore, what it does is to increase the value of p, but because ++ is used as postfix
the whole expression is evaluated as the value pointed by the original reference (the
address the pointer pointed to before being increased).
Notice the difference with:
(*p)++
Here, the expression would have been evaluated as the value pointed by p increased by
one. The value of p (the pointer itself) would not be modified (what is being modified is
what it is being pointed to by this pointer).
If we write: *p++ = *q++;
Because ++ has a higher precedence than *, both p and q are increased, but because both
increase operators (++) are used as postfix and not prefix, the value assigned to *p is *q
before both p and q are increased. And then both are increased. It would be roughly
equivalent to:
*p = *q;
++p;
++q;
It is recommended to use parentheses () in order to avoid unexpected results and to give
more legibility to the code.

The Assignment operation (=) between two pointers make them point to the same
thing . Consider the example below where the value of the pointer iptr is assigned to
another pointer variable of the same type pointer ptr .
ptr = iptr
After this assignment statement both the pointers ptr and iptr pointing to same value
thus making ptr point to whatever iptr pointed to .

x
1003

iptr

ptr

Pointer which refer to the same address location is called as sharing . Using this
feature of pointers ,a single memory structure in the memory can be shared by two or
more than two entities which is a very important goal.
Now observe the following statements :
int x ,y , * ptr1, * ptr2;
x = 45;
y = 90;
ptr1= & x;
ptr2= & y ;

whatever ptr2 is pointing to (here y) is set equal to whatever ptr1 is pointing to (here
x) , Thus y takes on the value of x and become 45.
Little more complicated manipulation of pointers is also possible like :
consider the following :
ptr = & x;
//

This statement makes ptr points to x

y = * ptr + 1;
This statement gets whatever ptr points at , adds 1 to it , and assign the final value to y;
if the value of x is 57 the y will display the value 58.
consider another statement like
*ip = 0
This statement whatever ip is pointing to will be set to zero. i.e. x will become zero.

MYNOTES

incrementing a pointer by 1 makes it point to memory location given by the


formula new address = old address+ scaling factor.

Decrementing a pointer by 1 makes it point to the memory location given by


the formula :
newaddress = old address scaling factor

Both addition and subtraction operation depend upon the size of data type pointer

variable points to.


Both the increase (++) and decrease (--) operators have greater operator precedence than

the dereference operator (*),


The Assignment operation (=) between two pointers make them point to the same thing

7.6Pointer and arrays


There is a strong relationship between the pointer and the arrays. Any operation which can be
performed using array subscripting can also be performed using pointers .The pointer version
will be generally faster than the array version of that program.
consider the following declaration :
int list[10];
this defines an array of 10 memory locations which can store 10 integer numbers ,which can be
referred as list[0] list[9].
List array can be represented as :

To access the elements of the array, subscript can be used . like a[8] refer to the 8 th
element of the array i.e. 34 . The notation a[i] refers to the i th element of the array. But
have you ever think that, what the variable list contains without the subscript ?

The list contains the address of the first element of the array . Since a pointer is a
variable which contains the address of another variable., it is evident that list is also a
pointer variable because it contain the address of the first element of the array.
So what it is pointing to ? list is pointing to the first element of the array.

now if you will give the statement


cout<< *list ;
it will display the value 6
Thus now it is clear that name of the array is actually a pointer that points to first
element of the array.
Remember
The name of the array always contain the address of the first element of the array.
As per pointer arithmetic adding 1 to pointer i.e. list +1 will point to the next object of
the array ,hence list +1 gives the address of the second element , the list +2 gives the
address of the third element .list + i gives the address of the (i+1) th element of the
array.
To display the values of the fifth element of the array we can write any of these
statements :
cout<< list[4];
cout<< * (list+4);

we can change or manipulate the content of the array using pointer references like

* (list + 4) =15

The parentheses are needed in the above statement because the unary ``contents of''
operator * has higher precedence (i.e., binds more tightly than) the addition operator. If
we wrote *list + 4, without the parentheses, we'd be fetching the value pointed to by
list, and adding 4 to that value. The expression *(ip + 1), on the other hand, accesses
the fifth value of the array

Remember

Reference to list[i] can also be referred as *(list + i) where list if the name of the array.
Both the two forms are equivalent .
Also &list[i] and list+i are identical, as list +i is the address of the (i+1) th element And
&list[i] is also refers to the address of the (i+1)th element of the array.
There is only one difference between an array name and the pointer . A pointer is a
variable so
int * ptr;
ptr = list;
variable

// assigning address of the first element to another pointing

ptr ++ is a valid operation and is legal.


but an array name is constant pointer variable whose value cannot be changed .hence
the operation like list++ is not a valid operation.
remember : Array name is a constant pointer
Example : 7.6 Program to calculate the sum of all the array elements using array
variable and pointer variable :
Ans
Using Array Subscript
#include <iostream.h>
void main()
{
int a[10];
cout <<Enter the elements of the array :;
int sum = 0;
for (int i=0; i<10; i++)
{
cout<<Enter the element : ;
cin>>a[i];
sum += a[i];

}
cout<< Sum of all the elements of the array is :<< sum
}
Using Pointer varaible
#include <iostream.h>
void main()
{
int a[10];
cout <<Enter the elements of the array :;
int sum = 0;
for (int *p=a ; p<a+10; p++)
{
cout<<Enter the element : ;
cin>>a[i];
sum += *p;
}
cout<< Sum of all the elements of the array is :<< sum
}

Example : 7.7
Write the output of the following :
(Assume that the base address of the array number is 5020)
#include <iostream.h>
int main()
{
int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
cout << "An integer occupies " << sizeof(int) << " bytes\n";
cout << "\n Number: " << Number;
cout << "\n&number[0]: " << &number[0] << endl;
cout << "\n Number+1: " << Number+1;
cout << "\n&Number:[1] " << &number[1] << endl;
cout << "\n Number+2: " << Number+2;
cout << "\n&Number:[2] " << &number[2] << endl;

return 0;
}
This would produce:
Output :
An integer occupies 4 bytes
Number: 5020
&number[0]: 5020
Number+1: 5024
&Number:[1] 5024
Number+2: 5028
&Number:[2] 5028

Remember : , By adding numbers to the name of the variable, we are able to get the address of any
member of the array.

From the above declaration it can be derived that


Pointers do not have to point to single variables. They can also point at the cells of an array i.e. it
can point to first element of the array that means the array can also be declared like this

int * list;

//Array can be declared using pointers

Reading and writing in this type of array can be take place using the following method :
Example 7.7 Reading and writing of arrays when it is declared as pointers.
#include<iostream.h>
void main()
{
int *list ;
for (int i=1; i<=5;i++)
{
cout<<"Enter a number: ";
cin>>*(list+i);
// reading of array elements
}
cout<<"The elements of the array are :"<<endl;t
for (i=1; i<=5 ;i++)
cout<<*(list+i)<<endl;
}

// display of array elements

output
Enter a number: 12
Enter a number: 34
Enter a number: 56
Enter a number: 78
Enter a number: 89
The elements of the array are :
12
34
56
67
78

Pointers are not restricted to integers only . It can also be used with character arrays as explained
in the next section of this chapter.

MYNOTES

The name of the array always contain the address of the first element of the array.

Reference to list[i] can also be referred as *(list + i) where list if the name of the array.
Both the two forms are equivalent .

Also &list[i] and list+i are identical, as list +i is the address of the (i+1)th element And
&list[i] is also refers to the address of the (i+1)th element of the array.

Array name is a constant pointer

By adding numbers to the name of the variable, we are able to get the address of any
member of the array.

7.6 Pointers and strings


String are one dimensional character arrays character arrays in C++ which is terminated
by NULL character i.e. /0. to define a string we can give the statement like

char str[10]=Hello;
this statement will define a string of 9 characters and last character is reserved for the
null character. It can be represented in the memory like this :

\0
101

101

100

100

100

100

100

100

100

100

100

Like, the integer arrays the name of the string array also contain the address of the first
element of the array .In the diagram address of the first element is 1003 . Hence the str
contains this value. Since str contain the address , it can be called as a pointer variable,
but it is a constant pointer variable whose value cannot be changed .
so a string can also be defined like
char *str = Hello;
But there is a one very important difference between the two declarations :
char str1[10]= HELLO;
char * str2 = HELLO;
str1 is an character array to hold the sequence of characters .str1 contains the address of
the first element of the array. str1 always refer to the same storage location which cannot
be changed .because str1 is a pointer constant.
on the other hand str2 is pointer to a character whose value can be modified as and
when required .

Both str1 and str2 are point to H and the location 1003 but value of str1 cannot be
modified. It will remain same throughout the execution of the program but the value of
str2 can be manipulated.

Example 7.8 Code to compare two strings


#include<iostream.h>
#include<stdio.h>
char *msg1, *msg2;
void main()
{
cout << "Enter a String 1:";
gets(msg1);
cout<<"Enter String 2:";
gets(msg2);
char *ptr1,*ptr2;
for (ptr1=msg1,ptr2=msg2;(*ptr1==*ptr2 && *ptr1!='\0'&& *ptr2!='\0');ptr1++,ptr2++);
if (*ptr1=='\0'&& *ptr2=='\0')
cout<<"\nTwo strings are identical";
else
cout<<"\nStrings are not identical";
}

output
Enter a string 1 : Archana
Enter a string 2 : Archana
Two strings are identical
Example : 7.9 To count length of the string
#include<iostream.h>
#include<stdio.h>
void main()
{
int count=0;
char *p;
cout<<Enter the string ;
gets(p);
for ( ; *p!='\0'; *p++)
{ count++; }
cout<<The length of the string is :<< count;
getch();
}
Output
Enter the string : Hello
Length of the string is : 5

Example : 7.10

Program to copy one string into another

#include<iostream.h>
#include<stdio.h>
char *my_strcpy(char *destination, char *source)
{
char *p = destination;
while (*source!='\0')
{
*p++ = *source++;

}
*p = '\0';
return destination;
}
int main(void)
{
char * strA, *strB;
cout<<"Enter string :";
gets(strA);
strB=my_strcpy(strB,strA);
cout<<"\nThe copied string is :";
puts(strB);
}
output
Enter string : programming
The copied string is : programming
Example 7.11

Program to concatenate two string

#include<iostream.h>
#include<stdio.h>
void concat( char *, char *, char * );
/* this functions copies the strings a and b to the destination string c */
void concat( char *a, char *b, char *c)
{
while( *a )
{
/* while( *c++ = *a++ ); */
*c = *a; ++a; ++c;
}
while( *b )
{
*c = *b; ++b; ++c;
}
*c = '\0';
}

main()
{
char *string1;
char *string2;
char *string3;
cout<<"Enter the string 1:";
gets(string1);
cout<<"\nEnter the string 2:";
gets(string2);
concat( string1, string2, string3);
cout<<string3;
}
}

output
Enter the string 1: object
Enter the string 2: oriented
object oriented
Example :7.12

To count the number of vowels in a string

#include<iostream.h>
#include<conio.h>
const int size = 7;
char str[size] = "Computer Science";
int vowels = 0;
for (char *Ptr = str; Ptr < str + size; Ptr++)
{
switch (*Ptr)
{ case 'A':
case 'a':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':

case 'U': vowels++; break;


}
}
cout << str << " has " << vowels << " vowels" << endl;
}
output
Computer Science has 6 vowels

This program uses a pointer to step through each of the elements in an array. Each element is
dereferenced by the switch expression, and if the element is a vowel, vowels is incremented. The
for loop then uses the ++ operator to advance the pointer to the next character in the array. The
for loop terminates when all characters have been examined.

MY NOTES

one dimensional character arrays can be declared by declaring a pointer and initializing it .
This is because the name of a character array is actually a pointer to the first element of the
array.
Character array can be printed using the pointer name only.
Declaration of a character type pointer does not assign any value to it .Therefore it cannot be
used to input strings, unless initialized.

7.7 Multidimensional Arrays and Pointers


consider the definition in which we create two dimensional arrays
int m[5][6];
int * b[5];
This declaration of b creates five pointers and each pointer points to an array of
integers.As per the above definitions the locations m[2][3] and b[2][3] both are
referring to a single integer ,but the array m is a true two dimensional array in which 5 x
6 =30 integer locations are reserved for the elements of the array. For b the definition
only allocates 5 pointers and does not initialize them (initialization can be done
explicitly with code ).Compiler will reserve the memory space for the five pointers.

The biggest advantage of the pointer array is that rows of the array may be of variable
length. Each element of B need not point to six elements. some may point to two
elements , some points to six elements , some points to none at all , since the compiler
cannot predict and cnnot decide on the number of members of each array . To access the
first pointer, you would type *(b+0), which is the same as *(b) or *b. The second pointer
can be accessed with *(b+1). Keep in mind that, *b is a pointer and not a value.
Therefore, to access a member of the array, you must first specify the desired pointer.
Then, using its index, you can get the corresponding value.
We can also declare two dimensional character array as :
char * name[5];
here five pointers are being declared , each of which is pointing to character . since one
pointer to a character can be used to represent a string , a set of five strings can be
represented as array of five character pointers.
After declaration the individual strings can be initialized by separate assignment
statements like :
name[0]= Monika;
name[1]=Rachit
name[2]=Himanshi;
name[3]=Hrishabh;
or it can also be initialized as follows :
char *name= { Monika,
Rachit,
Himanshi,
Hrishabh
};

Advantage of having an array of pointers is that


1. As we have discussed above the ,that each element of name can point to varable
length string
2. Manipulation of strings become convenient . For example we can write
name[0]=Monika
which is not possible in normal character array. In normal array we need to use strcpy
function to copy string literal into string variable like
char str[10];
str=Hello ;
// Invalid statement
strcpy(str,hello); //correct statement

MY NOTES

Two dimensional arrays can also be declared using pointers.


A set of strings can be declared as an array of pointers to characters.
It may be initialized by assigning values to one string at a time or all at
one time at the time of declaration .

7.9Pointers to structures
As we know, we can declare the form of a block of data containing different
data
types by means of a structure declaration . consider the example of
employee struct
which contains the following elements :
struct employee
{
char ename [20];
int ecode;

float salary;
}
just like another data types we can also declare the pointer variables which
can store the address of the structure variable .
employee e;
employee *sptr;

//declaration of structure variable


//declaration of a pointer to a structure

similarly like arrays ,structure variable name contain the address of the first
element of the array .
sptr = &e;

//assign sptr as pointer to the structure

struct employee
{
char ename[30];
int ecode;
float salary;
};
see, normally structure members are accessed through structure variables
using . operator
like .
Example 7.13
#include <iostream.h>
#include <string.h>
void main()
{
employee e;
strcpy(e.ename, "Mr. Adish");
e.ecode = 1001;
e.salary = 31000.56;
cout << e.ename << endl << e.ecode << endl << e.salary << endl;
}
Now we will see how through structure pointers sptr , defined above we will
access the members of the structure. Structure members are access through
arrow operator () . To refer to the structure members using operator the
general form is
structure pointer
like sptr -> ename,

structure member
sptr->ecode , sptr-> salary

Let us see this program how we can access the structure elements in the
program:
Example 7.14
#include <iostream.h>
#include <string.h>
struct employee
{
char ename[30];
int ecode;
float salary;
};
void main()
{
employee e, *sptr;
sptr =&e;
strcpy(sptr->ename, "Mr. Adish");
sptr->ecode = 1001;
sptr->salary= 31000.56;
cout << sptr->ename << endl << sptr->ecode << endl << sptr>salary << endl;
}
Pointers to structures are very useful when the whole structure is passed as
the arguments .
We know the name of an array stands for the address of its zeroth element the same concept
applies for names of arrays of structures. Suppose item is an array variable of struct type product.
Consider the following declaration:
struct product
{
char name[30];
int manufac;
float net;
};
product item[2],*ptr;
this statement declares item as array of two elements, each type struct products and ptr
as a pointer data objects of type struct products, the assignment

ptr=item;
would assign the address of zeroth element to product[0]. Its members can be accessed
by using the following notation.
ptr- >name;
ptr- >manufac;
ptr- >net;

The symbol - > is called arrow pointer and is made up of minus sign and greater than
sign. Note that ptr- > is simple another way of writing product[0].
When the pointer is incremented by one it is made to point to next record ie item[1]. The
following statement will print the values of members of all the elements of the product
array.
for (ptr=item; ptr< item+2; ptr++)
cout <\n<< ptr- >name<<endl<<ptr- >manufac<<endl<<ptr- >net;
We could also use the notation
(*ptr).number
to access the member number. The parenthesis around ptr are necessary because the
member operator . has a higher precedence than the operator *

7.9 Pointer to objects


We have already learned that :A class is an expanded concept of a data structure:
instead of holding only data, it can hold both various type of data and functions which
can operate on that data.
An object is an instance of a class. In terms of C++ variables, a class would be the type,
and an object would be the variable.
Rules of defining class object pointer is similar to defining pointer to structure variable
as we have discussed above .C++ allows to create pointers that point to classes. Once

you define a class it becomes a valid type, & we can use the class name as the type for
the pointer. These pointers which are pointing to class objects are called object
pointers.
Let us define a class bank:
Example 7.15
class Bank
{
int accountno;
char type;
char cust_name[20];
float balance;

public:

void readdata ( )
//Function to read the values of data members
{
cout<,Enter account number :;
cin >>accountno;
cout<,Enter type of account (S/C) :;
cin >>type;
cout<,Enter customer name:;
cin >>cust_name;
cout<,Enter the balance amount :;
cin >>amount;
}
void show()
//Function to show the values of data members
{
cout << Account deatials ;
cout<<Account number : << accountno;
cout<< Account Type :<< type;
cout<< Customer Number :<< cust_name;
cout<<Balance Amount :<< amount ;
}
float deposit (float amt)
{
balance = balance+ amount ;
return balance;
}
float withdraw ( float amt)
{
balance = balance amount;
return balance;

}
};
To declare a class pointer of bank type we shall write :

bank

* bptr ;

class name

pointer to class

where bank is the already defined class . While accessing the members of the class the
arrow operator ()instead of (.) operator is used . We cannot access the private
member of the class .A pointer can point to only public members of the class .let us see
how we can access the public member of the class through class pointer .Use ()
operator to access the data members of the class .
void main()
{
bank b , *bptr;
bptr = &b;
bptr readdata();
bshow();
}

// calling of public members using object pointers

Example : Show use of pointers to class objects


#include <iostream.h>
#include <string.h>
class student
{
private:
char course[10];
char name[30];
public:
void setdata(int *x, char *c);
void display(void);
};

void main()
{
worker *PGraduate, *graduate; // Declared as pointer to class object
pgraduate = new student;
graduate = new student;
pgraduate->setdata(MSc(OR), " Mudit Jain");
graduate->setdata(BSc(CS), " Sushmita Gera");
pgraduate->display();
graduate->display();
}
void student::setdata(int *i, char *s)
{
strcpy(course ,i);
strcpy(name, s);
}
void student::display(void)
{
cout << name << " is doing " << course << endl;
}

Array of Objects
We can also declare the array of objects like :
bank b[10];
Array name always contains the address of the first element in the array. It means the array name
is a pointer as it is holding address . If we make an object pointer, pointing to the first element of
the array then incrementing a pointer will point to the next element of the array
bank

b[10],*bptr;

this statement declares b as an array of ten elements, each type class bank and bptr as
a pointer data objects of type bank. The assignment
bptr= b;
would assign the address of zeroth element b[0] to bptr. Now the class members can be
accessed by using the following notation.

bptr- >readdata();
bptr->show();
The symbol - > is called arrow pointer and is made up of minus sign and greater than
sign. Note that bptr- > is simple another way of writing b[0].
When the pointer is incremented by one it is made to point to next record i.e .b[1]. The
following statement will print the values of members of all the elements of the product
array.
for (bptr=b; ptr< b+2; bptr++)
cout <\n<< bptr- >show();

// displaying all the objects of the array

Passing object pointers to functions


A whole class object may be returned or pass by pointers easily
,with in a function for better efficiency .

A class object passed/returned by pointers avoids creation of temporary objects.


Temporary objects call constructors and destructors (which is inefficient).
Passing/returning by pointers doesn't create temporary objects because a pointer only
stores the address to an object that already exists.
Given:

class Book
{
//...
};
class Backpack
{
public:
Book * getContents();
void setContents(Book * bk);
private:
Book myText;
};
Book& Backpack::getContents()
{

//function returning pointer to class

//function passing object pointer as arguments

return myText;
}
void Backpack::setContents(Book& bk)
{
myText=bk;
}
The member functions getContents() and setContents() use references to avoid
inefficient temporaries:
int main()
{
Book fiction;
Book somebook;
Backpack myPack;
myPack.setContents(fiction); // in setContents source, bk is a reference
// to fiction, not an inefficient temporary

somebook=myPack.getContents(); // myText is returned by reference


return 0;
}

7.10

Pointers and constants

You have already know that const qualifier is used to declare symbolic constants ,the
values which should not be modified. The same keyword is used to define the pointer
constants .
A constant pointer means that the pointer will always point to the same address. Its
address cannot be modified . To define a const pointer , type the const keyword on the
left side of the data type of the pointer variable .

int * const ptr =&x;


where ptr is a constant pointer pointing to a integer . constant pointer should be
initialized at the time of declaration only.

const int * ptr;


This statement define a pointer which is pointing to a constant value, means
the statements for changing the value ptr is pointing to will not be executed
like
statements
*ptr =6 ;
//invalid statement : try to modify the value of x

const int * const ptr;


This statement define a constant pointer which is pointing to a constant
value, means the statements for changing the value of ptr or the value ptr is
pointing to will not be executed like
statements
*ptr =6 ;
//invalid statement : try to modify the value of x
ptr++;
// invalid statement : try to modify constant pointer

Example 7.15
#include<iostream.h>
#include<conio.h>
int x=10;

int * const cptr = &x;

void main()
{
clrscr();
cout<<"value of ptr : "<<*cptr;
*cptr=5;
cout<<"new value of ptr is :"<<*cptr;
getch();
}

This statement will define a


constant pointer variable
cptr , which is pointing to the
same address &x throughout
the execution of the program

Constant pointers
can be
dereferenced and
values they are
pointing to can be

MYNOTES

A non-const pointer can be redirected to point to other addresses.


A const pointer always points to the same address, and this address cannot be changed.
A pointer to a non-const value can change the value it is pointing to.

A pointer to a const value treats the value as const (even if it is not), and thus cannot change
the value it is pointing to.

7.12

Pointers and Function argument

A pointer can also be pass as an argument to a function It is used to pass the single element as
well as the whole array . Here we modified the concept of passing arguments to functions : In XI
class we have learned that there are two ways to pass arguments to function.
1. Call by value : In this method value of each actual argument is copied in the calling
function is copied onto the corresponding formal arguments of the called function .

7.12.1

Call by value

#include <iostream.h>
void somefunc(float fvar)
{
fvar=99.9;
}
int main()
{
float fl=4.37;
somefunc(fl);
cout << fl << endl;
return 0;
}
This code will display the value 3.14. This method is pass by value .
when somefunc(f1) is called .fvar is created as a separate variable & the value of f1 is transferred
into another variable called fvar.

In the function the statement fvar=9.99 will change the value of fvar to 9.99

After the function execution is over the control return to the main function &
display the value of f1 which is unchanged i.e. it will display 4.37.

7.12.2 Call by reference :


In the situations where we would like to change the values of the variables in the calling
program then we pass the parameter in the function be reference . When parameters are
passed by reference then the formal parameters in the called function become references
(or aliases) to the actual parameters in the calling function . This means that the function
does not create its own copy of original values ,but it works on the original data hence
the changes done in the formal variables are reflected back in the actual arguments of
the calling program.
#include <iostream.h>

void somefunc(float & fvar)


{
fvar=99.9;
}
int main()
{
float fl=4.37;
somefunc(fl);
cout << fl << endl;
return 0;
}

so any change in the fvar is reflected back in the f1 . Actually both the variables are
representing the same memory location . Thus in this method function works with the
original arguments , and the values are not duplicated .The call by reference method of
sending arguments to function is more efficient as it need to pass only the address of the
object not the entire object .This method avoids createation of temporary objects
because reference is nothing but alias to an object that already exists.

7.12.3

Call by Pointers.

Like other variables, a pointer can be passed to a function. Passing a pointer as an argument

to a function is similar to the method of passing argument by reference . They both


permit the variable to be modified in the calling program without creating its duplicate
copies of the arguments .In call by reference method a reference or alias of the original
variable is created , while in call by pointer method pointer to the original variable is
created .

Pointer argument enables a function enable a function to access and change objects in
the function that called it .
Example : 7.16 Two versions of a program to swap values of two variables using
function swap () are shown here .note the change in the syntax of both methods.
1. pass arguments by reference
2. pass arguments by pointers
By passing reference

By passing Pointers

#include<iostream.h>

#include<iostream.h>

void main()

void main()

void swap(int & , int &);

void swap(int *x , int *y);

cout <<Enter the values of a and b :;

cout <<Enter the values of a and b :;

cin>>a>>b;

cin>>a>>b;

cout<<\n Original values are :;

cout<<\n Original values are :;

cout<<\n a = <<a;

cout<<\n a = <<a;

cout<<\nb = << b;

cout<<\nb = << b;

swap (a, b);

swap (a, b);

cout<<\n Swapped values are :;

cout<<\n Swapped values are :;

cout<<\n a = <<a;

cout<<\n a = <<a;

cout<<\nb = << b;

cout<<\nb = << b;

void swap (int & x, int & y)

void swap (int * x, int * y)

int temp;

int temp;

temp = x;

temp = *x;

x = y;

*x = *y;

y = temp;

*y = temp;

Output

Output

Enter the values of a and b : 12

Enter the values of a and b : 12

45

45

Original values are :

Original values are :

a = 12

a = 12

b = 45

b = 45

Swapped values are :

Swapped values are :

a = 45

a = 45

b = 12

b = 12

Passing arrays to the function


The name of the array allows the compiler to pass the whole array to the function .
Instead of passing an array as argument, instead of this we can use a pointer .Once a
pointer has been initialized as holding the address of an array, the name of the array
and the name of the pointer pointing to the same address. This means ,the name of the
pointer can be used ,when calling such a function.
example below will show how the whole array can be assed using pointers :
Example : 7.17 Showing passing arrays as pointers
#include <iostream.h>
int Arraysum(int *list, int size)
{
int sum = 0;
for(int i = 0; i < size; i++)
sum += list[i];
return Sum;
}
int main()
{
int number[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int *ptr = number;
int no_of_elements = sizeof(number) / sizeof(int);
int Value = Arraysum(ptr, no_of_elements);
cout << "Sum of numbers: " << Value;
return 0;
}

Similarly two dimensional arrays can also be passed to the function except a variable that points
to a two-dimensional array, provide the type of variable followed by an asterisk that indicates
that the argument is a pointer, and followed by a pair of square brackets. like for calculating the
sum of numbers of double dimensional array we can write
#include <iostream>
using namespace std;
void Display(int *List[]);
int main()
{
int number[2][6] = { { 31, 28, 31, 30, 31, 30 },
{ 31, 31, 30, 31, 30, 31 } };
int *ptr[2];
*ptr = number[0];
(*ptr)[0] = number[0][0];
(*ptr)[1] = number[0][1];
(*ptr)[2] = number[0][2];
(*ptr)[3] = number[0][3];
(*ptr)[4] = number[0][4];
(*ptr)[5] = number[0][5];
*(ptr+1) = number[1];
(*(ptr+1))[0] = number[1][0];
(*(ptr+1))[1] = number[1][1];
(*(ptr+1))[2] = number[1][2];
(*(ptr+1))[3] = number[1][3];
(*(ptr+1))[4] = number[1][4];
(*(ptr+1))[5] = number[1][5];
cout << "List of Numbers";
Display(ptr);

return 0;

void Display(int *list[])


{
cout << "\n(*ptr)[0]
cout << "\n(*ptr)[1]
cout << "\n(*ptr)[2]
cout << "\n(*ptr)[3]
cout << "\n(*ptr)[4]

= " << (*list)[0];


= " << (*list)[1];
= " << (*list)[2];
= " << (*list)[3];
= " << (*list)[4];

cout << "\n(*ptr)[5]

= " << (*list)[5] << endl;

cout << "\n(*(ptr+1))[0] = " << (*(list+1))[0];


cout << "\n(*(ptr+1))[1] = " << (*(list+1))[1];
cout << "\n(*(ptr+1))[2] = " << (*(list+1))[2];
cout << "\n(*(ptr+1))[3] = " << (*(list+1))[3];
cout << "\n(*(ptr+1))[4] = " << (*(list+1))[4];
cout << "\n(*(ptr+1))[5] = " << (*(list+1))[5] << endl;

Remember
In case a function that receives a pointer as argument is not supposed to modify the value of
the argument, you can pass the argument as a constant pointer. To do this, type the const
keyword on the left side of the data type of the pointer argument

7.12.4

Functions returning pointers

A function can also return pointers instead of a regular value like integer ,float or
double. The method of declaring return type of a function as a pointer , is same as other
data types. During the prototype declaration and definition of the function ,its return
type should be mentioned. You can specify this by typing the * operator on the left side
of the function's name . for example a function somefunc() returning pointer to double
type of data can be declared as follows :
double * somefunc ()
{
..
}
This declaration means that somefunc() is a function that return a pointer of type
double. Before the closing curly bracket of the function, remember to return address as
the return value.
Let us write a program that calculate the maximum of two numbers through a function
called max(). the function takes two arguments of integer numbers and return the
pointer to the greater number . The program is shown below :

Example :7.18
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
int *max(int &,int&);

// a function that return pointer to integer

void main()
{
clrscr();
int *m = NULL, x, y;
cout<<"Enter first number : ";
cin>>x;
cout<<"\n Enter second number : ";
cin>>y;
m=max(x,y);
cout<<"\nMax is : "<<*m;
getch();

// declare a pointer m pointing to integer

}
int *max(int &a, int &b)
{
if(a>b)
return &a;
else
return &b;
}
Output
Enter first number : 34
Enter second number :12
Max is :34

Another example of function returning pointer to a character .

Example : 7.19 program is used to search string1 into the another string2 . The function
getsubstr return the pointer to the beginning of the substring in string 2 ,if found
otherwise return NULL.
#include <iostream.h>
#include<stdio.h>
char *get_substr(char *sub, char *str);
int main()
{
char *substr,*str;
cout<<"Enter the string :";
gets(str);
cout<<"\nEnter the substring :";
gets(substr);
substr = get_substr(substr,str);
if (substr!='\0')
cout << "substring found: " <<substr;
else
cout<< "substring not found";
return 0;
}
char *get_substr(char *sub, char *str) // Return pointer to substring or null if not found.
{
int t;
char *p, *p2, *start;
for(t=0; str[t]!='\0'; t++)
{
p = &str[t];
start = p;
p2 = sub;
while(*p2!='\0' && *p2==*p)
// check for substring
{
p++;
p2++;
}
/* If at end of p2 (i.e., substring), then a match has been found. */

if(!*p2)
return start;

// return pointer to beginning of substring

}
return 0;
}
}
Output
Enter the string : Introduction to C++
Enter the substring : to
substring found: to C++
Enter the string : Computer Science
Enter the substring : SCIENCE
substring not found
Enter the string : Happy Birthday
Enter the substring : Birthday
substring found: Birthday

7.13 Pointers to pointers


C++ allows the use of pointers that point to pointers, that these, in its turn, point to data
(or even to other pointers). In order to do that, we only need to add an asterisk (*) for
each level of reference in their declarations:
char ch;
char *b;
char * *c;
ch = a;
b = & ch;
c= &b;
This, supposing the randomly chosen memory locations for each variable c, b and ch
could be represented as:
2000

3000

1000

ch

3000

1000

a
The value of each variable is written inside each cell; under the cells are their respective
addresses in memory.
The new thing in this example is variable c, which can be used in three different levels
of indirection, each one of them would correspond to a different value:

c
*c

**c has type char and a value of 'a'

has type char** and a value of 3000


has type char* and a value of 1000

Example 7.20
#include<iostream.h>
void main()
{
int a[] = {3 , 4 , 5 , 6}
int *p , **q , *s , *t , **ss;
p = a;
s = p + 1;
q = &s;
t = ( *q + 1);
ss = &t;
r = &ss;
cout << *p << \t << **q << \t << ***r << endl;}
}
Output
3
4

Dynamic initialization of the variables


Dynamic memory allocation is the ability of the C++ program to acquire block of
memory from dynamic memory pool called as free store or heap ,during run time of
the program .sometimes the program does not know the amount of data that needs to
be stored when the program is executing . in these situations program can request the
memory to be allocated form the dynamic memory pool . Now let us see how we can
allocate memory blocks during run time . There are two types of memory management
operators in C++:

new
delete

These two memory management operators are used for allocating and freeing memory
blocks in efficient and convenient ways.
We have seen the examples in which the array is declared like
int list [50];
reserve memory for 50 integers. Declaring array like this has one serious disadvantage
size of the array need to be predefined .In number of situations we does not know how
much memory we need until run time. so we define the bigger size array to hold the
largest number of elements which is the wastage of memory. These problems can be
avoided by dynamically allocating an array of the right size, or reallocating an array
when it needs to expand. Both of these are done by declaring an array as a pointer and
using the new operator to allocate memory, and delete to free memory that is no longer
needed.
Using pointers array can be declared like :
int *list;
Declaring the array like this has two main advantages
1. Size of the array need not be defined. so the problem of overutilization of memory
(declaring very large arrays) & underutilization (declaring smaller size arrays than
required ) may be avoided.
2. This is variable size arrays which can be expanded as per requirement by using new
operator.

7.14 The new Operator


In C++ provides the way to create dynamic variables . Dynamic variables are those
variables for which the memory space can be allocated or deallocated at the run time as
per the need of the program. Dynamic variables does not have name like static
variables , they are only referred by pointers.
Whenever we declare any pointer variables like
int * ptr;
ptr

This is a dangling pointer pointing to nowhere .we can connect this dangling pointer to
static variable or by dynamic variable.
we have already discussed how to connect a dangling pointer with a static variable like
int x;
ptr= & x;
now let us see how it can be connected with a dynamic variables.
The memory can be allocated during run time using a operator called new
the general form of using this operator is :

pointer variable
Pointer of
type
data type

= new
The
keyword

data type
Type of dynamic variable
required : Any valid C++
data type

This operator allocates memory of size ,equal to the size of specified data type and
return a pointer to the newly allocated area.
for example :

ptr = new int;

// the new operator allocates sufficient memory to hold


the object of datatype int and returns a pointer to its
starting point

This statement returns a address of the allocated location of memory which can hold
one integer. so ptr is a pointer pointing to the allocated memory space.

ptr

Dynamic
variable

Since dynamic variable does not have any name it is only referred through a pointer ,
pointing to it . Dynamic variables are never initialized by the compiler. Therefore, the
programmer should make it a practice to first assign them a value
*ptr = 40;

ptr

40

The assignment can be made in either of the two ways:

int *a = new int;


*a = 40;
or
int *a = new int(40);
Similarly the pointers to other data types can also be defined like :
char * cptr = new char ;
//declaration and assignment can be
combined
float * fptr = new float ;
now we can write
* cptr = a;
* fptr = 18.90;
Remember
Null pointer is returned by the new operator when there is insufficient memory
available for allocation.

Example : 7.21 Write a program to read the integer in dynamic variable ,calculates and
display its square .
# include<iostream.h>
main()
{
int *p;
p = new int;
cout<<\n Enter an integer : ;
cin >> *p;
cout<< \nSquare of the number is : <<*p * * p;
}
Output
Enter an integer : 5
Square of the number is : 25

To declare a variable that will point to a dynamically allocated array declare it as a


pointer to the element type.
For example
int * a = NULL
// pointer to an int, initially to nothing
this declaration creates a pointer but does not allocate the memory to it .
The syntax of dynamically creating an array of pointers is:

DataType *ArrayName = new DataType[Dimensions];


To start, type the kind of array you want to create: this is the DataType.
The ArrayName is the name of the array . Since this is a pointer, the array name must
be preceded by an asterisk operator.
Assign the new operator to the array name.
The new operator is followed by the same kind of data type of the first parameter,
DataType.

Dimension is included between square brackets, is the total number of elements to be


allocated in the array.
double *Distance = new double[12];

//Array of 12 elements of type double

int *pRanges = new int[120];

// Array of 120 elements of type integer

float *Prices = new float[44];

//Array of 44 elements of type float

After dynamically creating an array, the compiler allocates the necessary memory space
for all the members of the array, based on the data type and accommodating each. Just
like any variable, the memory allocated for each member of the array contains garbage.
It is the programmers responsibility to fill it up for appropriate values. This can be taken
care of by assigning a value to each member of the array .
Remember: Pointers may be subscripted just as arrays are.
Example : 7.22 To read in a number and allocates that size array.
int * a = NULL;
int n;
int* a = NULL;
// Pointer to int, initialize to nothing.
int n;
// Size needed for array
cout<<Enter the size of the array ;
cin >> n;
// Read in the size
a = new int[n];
// Allocate n ints and save ptr in a.
for (int i=0; i<n; i++) {
a[i] = 0;
// Initialize all elements to zero.
}
...
// Use a as a normal array
delete [] a;
// When done, free memory pointed to by a.
a = NULL;
// Clear a to prevent using invalid memory reference.

Similarly we can allocate the memory for the structure variable also using new operator.
we can directly read in the values in the structure variable.
Example : Showing the use of new operator with structure variable

Example 7.23
#include <iostream.h>
#include <string.h>
struct client
{
char name[30];
int acctnum;
double amount;
};
void main()
{
client *cl;
cl = new client;
// Allocating the memory for the structure client
strcpy(cl->name, "Mr. Adish");
cout<<The client details are :\n;
cl->acctnum = 10012;
cl->amount = 56700.56;
cout << \nClient name is :<<cl->name << endl ;
cout<< \nClient account number is :<<cl->acctnum << endl;
cout << \nClient Amount is : <<cl->amount << endl;
}
Output
Client name is : Mr. Adish
Client Address is : 10012
Client Amount is : 56700.56

7.14.2

Delete operator

To ensure safe and efficient, use of memory it is required that the memory reserved by
new operator must be released whenever it is not required in the program .This is done
through delete operator. Dynamic variable can be returned to the system by using this
an operator . General syntax of using this operator is

delete pointer variable ;


where delete is the keyword to delete a pointer variable

pointer variable is the name of the pointer whose allocated memory need to be deleted
for example :
delete ptr
This pointer will free the memory reserved by the pointer ptr. deleting the memory
does not delete the pointer but after delete statement we left with dangling pointers
which points nowhere.

ptr

Example : 7.24 To show the concept of new and delete operator


#include <iostream.h>
void main()
{
int *a= new a; //Allocates memory using new operator for storing a integer data type
*a=100;
cout << " The Output is ="<<a;
delete a;
//Memory Released using delete operator
}
output
The Output is : 100
Use [] when deleting arrays

You must specify "[]" when deleting an array, but not for a single value. It isn't possible
to delete only part of an array.
delete [ ] list

// where list is the dynamically created array pointer.

Common error
int *list[];

delete list

delete instead of delete[] when


deleting a dynamically allocated
array can cause data corruption
or other problems.

remember
Make a habit of assigning your pointers to 0 both when they are declared (unless assigned to
another address), and after they are deleted. It will save you a lot of grief.

7.14.3

Pointers and objects

Now we will learn how to use pointers to access the class objects and their members .a
pointer can point to an object created by the class .The declaration format is same as
other data types :
class student
{
int rno;
char name[20];
float marks;
public:
void getdata()
{
cout<<Enter the rollno : ;
cin>>rno;
cout<<\nEnter the name : ;
cin>>name;
cout<<Enter the marks : ;
cin>>marks;
}
void showdata()
{
cout<<\nRoll No : <<rno;
cout <<\nName :<< name;
cout<<\nMarks : <<marks;

}
};
let us declare an student type variable s and a pointer sptr to s as follows:
student * sptr;
sptr = new student
Now the public members of the dynamically allocated object can be accessed by the
object pointer sptr with the help of arrow operator ( ->) as shown below:
To process the above class we can write the main() function as follows:
void main()
{
student *sptr;
sptr=new student ;
sptr-> getdata();
sptr-> showdata();
}
If a class has a constructor with arguments and does not include an empty constructor
then we must supply the arguments when the object is created.
We can also create an array of class objects using pointers . for example :
student *sptr = new student [10];
This statement will create an array of 10 objects of class student .
Example :7.25 working on array of a class object with pointer.
#include <iostream.h>
#include <string.h>
#include<stdio.h>
#include<conio.h>
#include<iomanip.h>
class book
{
private:
float price;
char *title;
public:
void assign();
void display(void);
};
void main()

{
book * bptr[5];
int n=1;
int choice=0;
clrscr();
do
{
bptr[n]=new book;
bptr[n]->assign();
n++;
cout<<"\nDo you want to enter more books(1 for yes , 0 for no) : ";
cin>>choice;
} while (choice);
cout<<"\n\n";
cout<<"\nBook Details ";
cout<<"\n-------------";
for (int i=1; i<n; i++)
bptr[i]->display();
}
void book::assign()
{
cout <<"\n Enter the book name : ";
gets(title);
cout<<"\n Enter the price :";
cin>>price;
}
void book::display(void)
{
cout <<"\n"<< title << " is of price " << setprecision(5)<<price << " Rupees." <<
endl;
}
Output

7.14.4

Memory leaks

Dynamically allocated memory using new operator stays allocated until it is explicitly
deallocated or until the program ends
Def
A memory leak is a type of programming bug eats up the memory ,it occurs when a
program allocates more memory than it frees. These chunks of allocated memory which
is not released ,can not be reallocated or reuse are called memory leak or memory
bleeding . Memory leaks reduce the free memory while the program is running,
making less memory available not only to this program, but to other programs as well.
This way, an application can run out of memory and cause the system to run slowly or
crash. To prevent memory leaks, you need to know when they occur most frequently
and be careful with your use of the "new" and "delete" C++ operators. utmost care
should be taken while manipulating the dynamic variables . It is advisable to return a
dynamic variable whenever it is not required in the program. Following steps should be
taken to avoid the leakage of the memory.

1. The C++ operator "new" allocates heap memory. The "delete" operator frees heap
memory. For every "new," you should use a "delete" so that you free the same
memory you allocated:
char* str = new char [30];
// Allocate 30 bytes to store a string.
delete [] str;
// Clear those 30 bytes and make str pointer nowhere.

2. Before reallocating memory ,the previous memory should be releases . In the given
code below, str acquires a new address with the second allocation. The first address
is lost and so are the 10 bytes that it pointed to. Now they're impossible to free up
those 10 bytes , and you have a memory leak:

3.

Every dynamic variable (allocated memory on the heap) needs to be associated with
a pointer. When a dynamic variable becomes disassociated from its pointer(s), it
becomes impossible to erase. Again, this results in a memory leak:
int * aptr , * bptr

//declare pointers

ptr1 = new int;

//Allocate dynamic memory

ptr2 = new int;

//Allocate dynamic memory

*ptr1 = 20;
*ptr2 = 60;
ptr1 = ptr2;

// old address lost , memory leak

4. Consider the following function:


void somefunc()
{
int * p = new int;
}
This function allocates memory but never frees it using delete. A pointer you declare
in a function is allocated on the stack, but the dynamic variable it points to is
allocated on the heap. If you don't delete it, it will remain after the program exits
from the function:

7.15 This pointer


This pointer is a special type of pointer in C++ which contain the address of a class
object or the class instance ,that can access the member functions of the class. Note
the following points for this pointer

this pointer store the address of the class instance ,to enable pointer access of the
members to the member functions of the class .
this pointer is not counted for calculating the size of the object.

this pointers are not accessible for static member functions.

this pointers are not modifiable.

As

we know that C++ keeps only one copy of each member function and the data
members are allocated memory for all of their instances.
member functions are Common for all objects
getdat
a()
Object
1
ob1

setdat
a()

Object
2
ob2

Object
3
ob3

Consider a class ABC which is defined below


class ABC
{
int data;
public:
int getdata()
// function not using this pointer
{
return data;
}
void setdata(int newval) // function using this pointer
{
this->data = newval;
}
};
void main()
{
ABC ob1,ob2;
ob1.getdata();
}
This class which has two member functions getdata() and setdata() .The function call
ob1.getdata() will set the pointer this to the address of object ob1 .This unique pointer is
automatically passed to a member function when it is called . The call ob2.getdata() will
set the value of this pointer to the address of ob2 object.

ob1.getdata():
member functions are Common for all objects
getdat
a()
Object 1
ob1
1010

101
0

Object
2
ob2
1020

setdat
a()
Objec
t3
ob3
1030

this pointer

ob2.getdata():
member functions are Common for all objects
getdat
a()
Object 1
ob1
1010

102
0

Object
2
ob2
1020

setdat
a()
Objec
t3
ob3
1030

this pointer

the private variable of the data of class ABC can be accessed in its member function
setdata() :
this->data=newval ;

the same statement can also be referred as data=newval;


We have not been using this pointer for referring to private data of the class in their
member functions . One important application of the this pointer is to return the
address of the current object it points to .
retrun *this
will return the object that has called that particular member function .
This pointer is useful when we want to compare two or more objects inside a member
function and return the invoking object as a result.
consider another example

Example : 7.26
incentives.

To find out the details of the salesperson who is having maximum

#include<iostream.h>
#include<string.h>
class salesperson
{
char name[20];
float incentive;
public :
salesperson ( char *s , float a)
{
strcpy(name,s);
incentive=a;
}

Note that how


the address of
the current
object is
returned here
using this
pointer .

salesperson & salesperson ::maximum(salesperson &s)


{
if (s.incentive>=incentive)
return s;
else
return *this;

This function
call return the
object s1 , if
the incentive of
the salesperson
S1 is greater
than that of
s2 ,other wise it
will return the
object s2using

this .

}
void display()
{
cout<<"\n\nName : " <<name<<"\n";
cout<<"\nIncentive : "<<incentive<<"\n";
}
};
void main()
{
salesperson s1("Manu",3000),s2("Rupika",40000),s3("Anika",10000);
salesperson s=s1.maximum(s2);
s=s3.maximum(s);
cout<< "Salesperson getting maximum incentive is :";
s.display();
}

7.15 Self-referential structures


It is exactly what it sounds like: A structure which contains a reference to itself. When a
member of a structure is declared as a pointer to the structure itself then the structure is
called as self referential structure.. Generally nodes of linked lists are examples of self
referential structures - which refer to memory location of same type by storing a self
type pointer as a member Each node needs a reference to the next node in the chain.

struct node
{
int data;
node *next;
};

// <- self reference

The data member next of the structure can point to structure variable of type node
consider another example in which structure point contain a member variable next
which is pointer to the structure point itself.
struct Point
{
float x;
float y;
Point* next;
};
These linked structure has great potential and used in implementing data structures like
linked list , stacks , queues , tress dynamically..

7.16 Reference variables


A reference is nothing more than an alias. An alias means another name for the same
variable .Anything you do with a reference you are actually doing to the object you are
referencing. References are declared by using an ampersand (&) between the reference

type and the variable name. for example : an alias y for the variable x can be created as
int x;
int &y = x;
x=15

The ampersand in this context does not mean address of, it means reference to.
Now there are two names defined for the same memory location 1003 as shown in the diagram.

consider the following program code :


cout <<address of x is : << & x;
cout<<address of y is :<<&y
it will display
address of x is 1003
address of y is 1003
this shows both the alias variables has the same address.

x = 15;

// x is now 15

y = 7;

// x is now 7

cout<< x;

//displays 7

x ++;

// x is incremented to 8

cout <<y;

//displays 8

This shows any change made in the x is also reflected back in the y also and vice versa. y is just
the different name to the variable x.

Remember
References always point to valid objects, and can never be pointed to deal located
memory, references are safer to use than pointers.

Common errors
int Value = 5;
int &Refvalue = Value; // valid reference
int & val

References must be given value


upon declaration

//another reference variable which is not initialized

Common errors
int value1 = 5;
int value2=6
int &refvalue = value1; // valid reference
refvalue=value2;

The reference can not be redirected


to another variable

//assign value 6 to refvalue but does not change the reference

Remember
Because references always point to valid objects, and can never be pointed to deallocated
memory, references are safer to use than pointers.

Questions
Multiple choice questions
1.

Assume the variable declarations:


int F = 0;
int *ptr = &F;
Which of the following statements will change the value of F to 1?
a.
ptr++;
b.
F++;
c.
(*F)++;
d.
(*ptr)++;
For questions 2 through 3, assume that P and Q are pointers of the same type, and
that each has been assigned a value.

2. What comparison would determine whether P and Q have targets with the same
value?
a.
&P == &Q
b.
*P == *Q
c.
P == Q
d.
All of them
3. What comparison would determine whether P and Q have the same value?
a) &P == &Q
b) *P == *Q
c) P == Q
d) All of them
4. Consider implementing a function to dynamically allocate an array of integers
and set all its elements to zero:
void ZeroIt( _________A, const int Size)
{
A = new int[Size];
for (int Idx = 0; Idx < Size; Idx++)
A[Idx] = 0;
}
Which of the following choices for the blank preceding the formal parameter A is
best?
a.
int*
b.
int*&
c.
const int*
d.
int* const
e.
const int* const
5. #include <iostream.h>
int main()
{
char* p = NULL;
p = new char;
*p = 'x';
return 0;
}
What is the value of (*p)++;
a.
x
b.
y

c.
d.

x+1;
p+1

6. Which code fragment(s) could be inserted in the blank in order to safely initialize
each element of A to zero?
* p = &A[0];
for (int Idx = 0; Idx < Size; Idx++, p++)
{
__________;
}
a.
*A = 0;
b.
A[Idx] = 0;
c.
*p = 0;
d.
*Idx = 0;
7. Assuming only the initial declarations given above, what logical error(s) would
result if the following statement were executed: A = new int[2*Size];
a) A dangling pointer would result (a pointer whose value is the address of
memory that the program no longer owns).
b) A memory leak would result (the program would own memory that it could
no longer access).
c) Both a dangling pointer and a memory leak would result.
d) Neither a dangling pointer nor a memory leak, but some other logical error
would result.
5) No logical error would result.
8. void *ptr;
myStruct myArray[10];
ptr = myArray;
Which of the following is the correct way to increment the variable "ptr"?
a.
ptr = ptr + 1
b.
++(int*)ptr;
c.
ptr = ptr + sizeof(myArray);
d.
increment(ptr);
e.
ptr = ptr + sizeof(ptr);
9.
char* myFunc(char *ptr)
{

ptr += 3;
return (ptr);
}
int main()
{
char *x, *y;
x = "HELLO";
y = myFunc(x);
cout <<y;
return 0;
}
What will print when the sample code above is executed?
a.
y = HELLO
b.
y = ELLO
c.
y = LLO
d.
y = LO
e.
x=O
-----------------------------------10. char buf [] = "Hello world!";
char * buf = "Hello world!";
In terms of code generation, how do the two definitions of buf, both presented
above, differ?
a. The first definition certainly allows the contents of buf to be safely modified at
runtime; the second definition does not.
b. The first definition is not suitable for usage as an argument to a function call; the
second definition is.
c. The first definition is not legal because it does not indicate the size of the array to
be allocated; the second definition is legal.
d. They do not differ -- they are functionally equivalent.
e. The first definition does not allocate enough space for a terminating NULcharacter, nor does it append one; the second definition does.
11. char ptr1[] = "Hello World";
char *ptr2 = new char[5];
ptr2 = ptr1;
What is wrong with the above code (assuming the call to new does not fail)?
a.
There will be a memory overwrite.

b.
c.
d.
e.

There will be a memory leak.


There will be a segmentation fault.
Not enough space is allocated by the new.
It will not compile.

12.
int y[4]={6, 7, 8, 9};
int *ptr = y + 2;
cout<< ptr[1];

/*ptr+1 == ptr[1]*/

What is printed when the sample code above is executed?


a.
6
b.
7
c.
3
d.
9
e.
The code will not compile.
13. char * dwarves [] =
{
"Sleepy",
"Dopey" "Doc",
"Happy",
"Grumpy" "Sneezy",
"Bashful",
};
How many elements does the array dwarves (declared above) contain? Assume
the C compiler employed strictly complies with the requirements of Standard C.
a.
4
b.
5
c.
6
d.
7
e.
8
14.
char *buffer = "0123456789";
char *ptr = buffer;
ptr += 5;
cout <<ptr ;
cout <<buffer;

What will be printed when the sample code above is executed?


a. 0123456789
56789
b. 5123456789
5123456789
c. 56789
56789
d. 0123456789
0123456789
e. 56789
0123456789
15. Consider the following statements :
#include <iostream.h>
void main( )
{
int a=40,*ptr=&a;
char ch=M, &cho=ch;
cho+=a;
*ptr+=ch;
cout<<\n<<a<< <<ch<<endl;
}
Which of the following set of values will be displayed ?
(a)

157 , u

(b)

156 , t

(c)

157 , v

(d)

158, u

16. Which of the following expression would correctly add just 4 to a pointer p
pointing to an element of type struct abc ?
(a)

p+4

(b)

(struct abc * )((char *)p + 4 )

(c)

(struct abc * )((void *)p + 4 )

(d)

More than one of the above

17. Predict the output of the following code :


# include <iostream.h>
void func (int *ptr)
{ *ptr = 72 }
int main( )
{ int x = 10;
func ( &x );
cout << x; }
(a)
(b)
(c)
(d)

72
10
The program generates a compilation error
The Program generates a run time error

18. Study the following code :


main( )
{
char *p = NULL;
strcpy ( p , );
cout<<p;
}
What will be displayed if the above program runs :
(a)
NULL
(b)
Nothing will be displayed
(c)
Compiler cannot recognize in the strcpy function
(d)
Run Time error as p has not been allocated
Ans

161116-

b &d
b&c
a
a

271217-

b
c
d
a

381318-

c
a
b
b

4914-

d
d
e

SHORT QUESTIONS
1. WHAT WIIL BE OUTPUT OF FOLLOWING PROGRAM?
#include<iostream.h>
# include <conio.h>
void main()
{
clrscr();
int sum(int(*)(int),int);
int square(int);
int cube(int);
cout<<sum(square,4)<<endl;

51015-

b
d
a

cout<<sum(cube,4)<<endl;
getch();
}
int sum(int(*ptr)(int k),int n)
{
int s=0;
for(int i=1;i<=n;i++)
{
s+=(*ptr)(i);
}
return s;
}
int square(int k)
{ int sq;
sq=k*k;
return k*k;
}
int cube(int k)
{
return k*k*k;
}
Ans
Output will be
30
100
2. Pointers always contain integers Comment.
Ans Pointer variable always store address of a variable which is always an integer or
hexadecimal integers , So pointers always store integers.
3. Find the output of the following program (3)

# include<iostream.h>
#include<string.h>
class state
{
char * state_name;
int size;
public:

state( )
{ size=0;
state_name=new char[size+1];
}
state(char *s)
{ size = strlen(s) ;
state_name = new char[size+1];
strcpy(state_name,s);
}
void display()
{
cout<<state_name<<endl;
}
void Replace (state &a, state &b)
{
size = a.size + b.size;
delete state_name;
state_name = new char[size+1] ;
strcpy(state_name, a.state_name);
strcat(state_name, b.state_name);
}
};
void main( )
{
char *temp = "Delhi";
state state1(temp), state2("Mumbai"), state3("Nagpur"), S1, S2;
S1 .Replace(state1, state2);
S2.Replace(S1, state3);
S1.display( );
S2.display( );
}
Ans
Output
DelhiMumbai
DelhiMumbaiNagpur
4. Rewrite the following codes after removing errors, if any, in the following snippet. Explain each
error.
#include<iostream.h>
void main()

{
int x[5], *y, z[5]
for (i = 0; i < 5; i ++)
{
x[i] = i;
z[i] = i + 3;
y = z;
x = y;
}
}
Ans
#include<iostream.h>
void main()
{
int x[5], *y, z[5] ;
for (i = 0; i < 5; i ++)
{
x[i] = i;
z[i] = i + 3;
y = z;
x = y;
}
}

//
//

Semicolon missing ;
variable i' is not defined

// value of x cannot be changed , as x is a array name, which


//
is a pointer constant

5. Rewrite the following codes after removing errors, if any, in the following snippet. Explain
each error.
void main()
{
const int i = 20;
const int * const ptr = &i;
(*ptr)++;
int j = 15;
ptr = &j;
}
Ans
void main()
{
const int i = 20;
const int * const ptr = &i;
(*ptr)++;
int j = 15;
ptr = &j;

// Value of *ptr cannot be modified as it is a constant


//Value of ptr cannot be modified as it is also a constant

6.

Give the output of the following program:


void main()
{
char *p = Difficult;
char c;
c = ++ *p ++;
cout<< c;
}
Ans
E

7. Give the output of the following program:


void main()
{
int x [] = { 10, 20, 30, 40, 50}:
int *p, **q, *t;
p = x;
t = x + 1;
q = &t;
cout << *p << , << **q << , << *t++;
}
Ans
10, 30, 20

8. Give the output of the following program( Assume all necessary header files are
included) :
void main( )
{
char * x = teAmIndia;
char c;
c = ++ *x ++;
cout<<c;
}
Ans u
9. Give the output of the following program(Assume all necessary header files are
included) :
void main( )
{
char *x = teAmIndia;
char c;

c = ( *(x+1) ) ++ ;
cout<<c;
}
Ans e
10. What will be the output of the program( Assume necessary header files are included) :
#include<iostream.h>
void print (char * p )
{
p = "pass";
cout<<"value is "<<p<<endl;
}
void main( )
{
char * x = "Best of luck";
print(x);
cout<<"new value is "<<x<<endl;
}

Ans

Output
value is pass
new value is Best of luck
11. Give the output of the following program:
void main()
{
int arr[] = {2, 3, 4, 5};
int *ptr = arr;
int val = *ptr;
cout << val << endl;
val = *ptr ++;
cout << val << endl;
val = *ptr;
cout << val << endl;
val = * ++ptr; cout << val << endl;
}

Ans
output
2
2

3
4
12. Give the output of the following program.
#include<iostream.h>
#include<conio.h>
int a = 10;
int main( )
{
void demo ( int &, int , int *);
clrscr( );
int a = 20;
int b=10;
demo ( ::a,a,&b);
cout << ::a << "\t" << a << "\t" << b;
}
void demo ( int &x, int y , int *z )
{
a += x; y *= a; *z = a+y;
cout << x << "\t" << y << "\t" << *z << endl;
}
Ans

20
20

400
20

420
420

HIGH ORDER THINKING QUESTIONS


13. Answer the following g
1.
2.
3.
4.
5.
6.

In the declaration float *f the pointer variable f is pointing to a variable of type _______
Is the following declaration valid * ptr.
State true or false : In the declaration int * ptr1 an integer is being declared.
State true or false : Is a pointer is not initialized , there is a high chance of the program crashing.
Is the declaration : int x , * ptr is valid ?
The __________________ operator is used to get the address of the variable.

1.
2.
3.
4.
5.
6.

float
No, When the pointer variable is declared The type to which it is pointing must be decalred
False, A pointer to integer is declared not integer.
True
Yes, it is correct . Declaraction of a pointer with the same type of variables is valid.
&

Ans

14. void main()

{
const int i=20;
const int * const ptr=&i;
(*ptr)++;
int j=20;
ptr=&j;
}
(a) 20
(b) Error-Cannot Modify a Const Object
(c) garbage value
(d) None of these
Ans

(b)

15. #include<string.h>

Ans

#include<ctype.h>
void main()
{ int i;
char *p=Student;
char c;
for (i=1;i<6;i++)
{ if (i%2==0)
++p;
}
c=*p;
cout<<c; }
}
(a) d (b) S (c) u (d) None of these
(c)

16. Find the output :

void main()
{
char *str[]={Book,mbd,computer};
cout<<sizeof(str)<<sizeof(str[0]);
}
(a) 3 2 (b) 6 2 (c) 6 3 (d) None of these
Ans (b)

17. Find the output :

#include<iostream.h>
void func(int **p)
{cout<<**p;
}
void main()
{int a[3][4]= { 1,2,3,4,
4,3,2,1,
5,6,7,8,
};
int *ptr;
ptr=&a[0][0];
func(&ptr);
}
(a)1
(b) 4 (c) 5 (d) None of these
Ans (a)
18. Find the output :

void main()
{char far *S1,*S2;
cout<<sizeof(S1)<<Sizeof(S2);
}
(a) 4 4 (b) 2 4 (c) 4 2 (d) None of these
Ans (c) : size of far pointer is 4 bytes , and normal pointers are of 2 bytes on a 16 bit
computer.
19. Find the output :

void main()
{char a[]=Array;
char *b=Pointer;
cout<<sizeof(a)<<sizeof(b)<<endl;
cout<<sizeof(*a)<<sizeof(*b);
}
(a) 2 2 1 (b) 1 2 2 (c) 2 2 2 (d) None of these
Ans (d)
output
6 2
1 1

The sizeof(a) = 6 as it contains array a contains 5 elements plus one for the null character
sizeof(b) = 2 only he memory space for the pointer is reserved
sizeof(*a) = 1 sizeof(*b)=1 as they both are referring to characters.
20. .

Find the output of the following program :


#include<iostream.h>
void main()
{
int Numbers[] = {12,4,10,8};
int *ptr = Numbers;
for (int C = 0; C<3; C++)
{
cout<< *ptr << @;
ptr++;
}
cout<<endl;
for(C = 0; C<4; C++)
{
(*ptr)*=2;
--ptr;
}
for(C = 0; C<4; C++)
cout<< Numbers [C]<< #;
cout<<endl;
}

Ans

2@4@8@
4 # 8 # 16 # 20 #

21. Find the output of the following program code :

(i)

char *s1 , *s2;


s1 = BUTTER;
strcpy(s1 , strncpy( s1 , s2 , 3));

strnset( s1 , 77 , 3);
cout<<s1;
Ans

MMMTER

(ii)

int a[] = {3 , 4 , 5 , 6};


int *p , **q , *s , *t , **ss;
p = a;
s = p + 1;
q = &s;
t = ( *q + 1);
ss = &t;
cout << *p << \t << **q << \t << ss << endl;

Ans

0x123456(Hexa decimal value)

22. Write the output of the follwoing program segment


#include<iostream.h>
#include<string.h>
#include<ctype.h>
#include<stdio.h>
void main()
{
char *NAME="ComPUteR";
clrscr();
for(int x=0;x<strlen(NAME);x++)
{
if(islower(NAME[x]))
NAME[x]=toupper(NAME[x]);
else
if(isupper(NAME[x]))
if(x%2==0)
NAME[x]=tolower(NAME[x]);
else
NAME[x]=NAME[x-1];
}

puts(NAME);
}
Ans

cOMMuTEE

23. What will be the output of the following program :


#include<iostream.h>
#include<ctype.h>
#include<conio.h>
#include<string.h>
void changestring(char text[], int &counter)
{
char *ptr = text;
int length=strlen(text);
for(;counter<length-2;counter+=2,ptr++)
{
*(ptr+counter) = toupper(*(ptr+counter));
}
}
void main()
{
clrscr();
int position = 0;
char message[]= "Mouse Fun";
changestring(message,position);
cout<<message<< "@" <<position;
}
Ans

MouSe Fun@8

24. Find the output of the following program:


#include<iostream.h>
#include<string.h>
class student
{ char *name;
int I ;
public:
student( ) {I =0; name=new char [ I +1]; }
student (char *s)
{ I =strlen(s); name=new char[I+1];

strcpy (name,s);
}
void display( ) {cout<<name<<endl;}
void manipulate(student & a, student & b)
{ I = a.I + b.I;
delete name;
name=new char[I+1];
strcpy(name, a.name);
strcat(name, b.name);
}
};
void main( )
{ char * temp = Jack;
student name1 (temp), name2( Jill), name3(John),S1,S2;
S1 .manipulate (name1, name2);
S2.manipulate (S1, name3);
S1.display ( );
S2.display ( );
}
Ans
JackJill
JackJillJohn

25. Find the output of the following program:


#include<iostream.h>
#include<conio.h>

void main( )
{ int *PointerArray[10];
int marks [] = {75, 68, 90, 34, 0, 10, 90, 65};
clrscr();
for (int I = 0; marks [I]!=0; I++)
{ PointerArray [I]=&marks[I];
* (PointerArray[I]) += 5;
}
int index = 0;
while(index<I)
{ int p=*(PointerArray[index] );
if(p>=60)
cout<<p<< ", ";
index ++;
}

Ans
80 , 73 , 95,

26. Give the output of the following program :


#include<iostream.h>
#include<conio.h>
main( )
{
int a=0;
clrscr( );
char *name;
name= Internet Browsing;
for(a=0;a<=8;a++)
cout<<name[a+1];
cout<<endl;
cout<<name[a];
cout<<endl<<(int)name[a]-1;
getch( );
return 0;
}
Ans

Output
nternet B
B
65
40 Give the output of the following program :
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
main( )
{
clrscr( );
char *name;
int len=0;
name= "Object Oriented Programming";
len = strlen(name);

len = len-1;
for(int i=len;i>=0;i=i-2)
{
cout<<name[i]<<" ";}
cout<<endl<<i<<endl;
cout<<name[i+4]<<endl;
cout<<endl;
getch();
return 0;
}
Ans
output
gimroPdter cjO
-2
j
45 What is the output of the following program( Assume all necessary header files are
included) :
#include<iostream.h>
#include<conio.h>
#include<string.h>
void main( )
{
char * str = "TEACHER";
for ( int i = strlen(str) - 1 ; i >= 0 ; i --)
{
for ( int x = 0 ; x <= i ; x ++)
cout<<str[x] ;
cout<<"\n";
}
}
Ans
TEACHER
TEACHE
TEACH
TEAC
TEA
TE
T

46 What is the output of the following program( Assume all necessary header files are
included) :
void main( )
{
int * p[10];
int score[] = {80, 30, 74, 50, 34, 67,0, 98};
for ( int i = 0 ; score[i] != 0 ; i ++)
{
p[i] = & score[i];
*(p[i]) += 10;
}
int count = 0;
while( count < i)
{
int q = *(p[count]);
count++ ;
if(q > 50)
cout<<q<< , ;
}
}
47 What will be the output of the following program :
# include<iostream.h>
#include<ctype.h>
#include<conio.h>
#include<string.h>
void NewText(char str[ ], int & pos)
{
char * p = str;
int length = strlen(p);
for( ; pos < length - 2; pos += 2 , p++)
{
*(p + pos) = toupper(*(p+pos));
}
cout<<str;
}
void main( )
{
clrscr( );
NewText(Good Morning, 0) ;

}
48 What is the output of the following program( Assume all necessary header files are
included) :
# include <iostream.h>
# include<ctype.h>
#include<string.h>
#include<conio.h>
class country{
char * c_name;
int length;
public:
country( )
{
length = 0;
c_name = new char[length+1];
}
country(char * s)
{
length = strlen(s);
c_name = new char[length+1];
strcpy(c_name, s);
}
void display()
{
cout<<c_name<<endl;
}
void replace(country &a, country &b)
{
length= a.length+b.length;
c_name = new char[length+1];
strcpy(c_name, a.c_name);
strcpy(c_name, b.c_name);
}
};
void main( )
{
char *temp="India";
clrscr( );
country c1=temp, c2("Nepal"),c3;
c3.replace(c1,c2);

c3.display( );
getch( );
}

e) What will be the output of the following program:


[3]
#include<iostream.h>
#include<ctype.h>
#include<conio.h>
#include<string.h>
void PointersFun(char Text[], int &count)
{
char *ptr=Text;
int length=strlen(Text);
for(; count<length-2; count+=2, ptr++)
{
*(ptr + count) = toupper( * (ptr + count) );
}
}
void main()
{
clrscr();
int position=0;
char Data[]= ChangeString;
PointersFun(Data, position);

cout<<Data<< @<< position;


cout.write(Data + 3, 4);
}
12 Consider the following statements
Char ch,ch1=A;
Char *p,*p1=&ch1;
*p1=ch1+1;
*p=ch;
Suppose each character occupies 2 bytes of memory. If the value assigned to ch is stored in
address 0x22 and the value assigned to ch1 is stored in address 0x105 then
(i) what value is assigned to p1;
(ii) what is the value of *p1;
(iii) what value is assigned to ch?
(iv) What value is assigned to *p?

e) Find the correct possible output of the following program ( Consider all the header
files are present) .
struct card {
char suit[10];
int digit;
};
card* cards = new card[52]; // Allocate Memory
void createdeck()
{

char temp[][10] = {"Clubs","Spades","Diamonds","Hearts"};


int i,m=0,cnt=1;
for(i=1;i<=52;i++)
{

strcpy(cards[i].suit,temp[m]);
cards[i].digit=cnt;
cnt++;
if(i % 13 == 0)
{ m++; cnt=1; }

} }

card drawcard(int num)


{

int rndnum;
randomize();
rndnum = random(num)+1;
return (cards[rndnum]);

}
void main()
{

createdeck();
card c;
c = drawcard(39);
if(c.digit > 10 || c.digit == 1)
{

switch(c.digit)
{

case 11:

cout<<"Jack of ";

break;

case 12:

cout<<"Queen of "; break;

case 13:

cout<<"King of ";

case 1:

cout<<"Ace of ";

break;

} }
else
cout<<c.digit<<" of ";
cout<<c.suit;
delete[] cards;

//Deallocate memory

}
Outputs:
i)

Kind of Spades

ii)

Ace of Clubs

iii)

Ace of Diamond

iv)

Queen of Hearts

41. Give the output of the following program( Assume all necessary header files are
included)
:
void main( )
{
char * x = teAmIndia;
char c;
c = ++( *(x+1) );
cout<<c;
}

17 What will be the output of the following program:


#include<iostream.h>
#include<ctype.h>
#include<conio.h>
#include<string.h>
void changestring(char text[], int &counter)
{
char *ptr = text;
int length=strlen(text);
for( ;counter<length-2; counter+=2,ptr++)
{
*(ptr+counter) = toupper(*(ptr+counter));
}
}
void main()
{
clrscr();
int position = 0;
char message[]= Pointer Fun;
changestring(Message, position);
cout<<message<< @ <<position;
}
#include <iostream.h>
#include <ctype.h>
#include <string.h>
#include <conio.h>
void main()
{
clrscr();
char * NAME = "a ProFiLe";
for (int x = 0;x<strlen(NAME) ; x++)
if(islower (NAME [x]))
NAME [x] = toupper (NAME [x]);
else
if (isupper (NAME [x]))
if (x % 2 != 0)
NAME[x] = tolower (NAME [x-1]);
else
NAME [x]-- ;
cout<<NAME<<endl;
}
#include <iostream.h>
#include <ctype.h>
#include <string.h>
#include <conio.h>
void main()
{
clrscr();
char *s = "GOODLUCK";
for (int x = strlen(s)-1 ; x>=0; x--)
{
for ( int y=0; y<=x; y++) cout<<s[y];

cout<<endl;
}
}
#include <iostream.h>
#include <ctype.h>
#include <string.h>
#include <conio.h>
void main()
{
int a = 32, *X = &a;
char ch = 65, &eco = ch;
eco += a;
*X += ch;
cout << a << ',' << ch << endl;
}
#include <iostream.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
void Newtext(char String[], int &Position)
{
char *Pointer = String;
int Length = strlen(String);
for ( ; Position<Length - 2; Position+=2, Pointer++)
{
*(Pointer+Position) = toupper(*(Pointer + Position));
}
}
void main()
{
clrscr();
int Location = 0;
char Message[] = "Dynamic Act";
Newtext(Message, Location);
cout << Message << " # " << Location;
}
#include <iostream.h>
void main()
int x[] = {10, 20, 30, 40,50};
int *p, **q, *t;
p = x;
t = x + 1;
q = &t;
cout<<*p<<","<<**q<<","<<*t++;
}
#include <iostream.h>
#include <conio.h>
struct Game
{
char Mag[20]; int Score;
};
void main()
{
clrscr();
Game M={"Tiger", 500};
char *Choice;
Choice = M.Mag;
Choice[4] = 'P';
Choice[2] = 'L';
M.Score+=50;
cout << M.Mag << M.Score << endl;
Game N = M;

N.Mag[0] = 'A'; N.Mag[3] = 'J';


N.Score -= 120;
cout << N.Mag << N.Score << endl;
}

Q1 (i)

Find the mistake , if any in the following definition and make the
necessary corrections :
char *ptr , s[10];
ptr = s[6];

(ii)

Distinguish between :
int * ptr = new int(5);
int *ptr = new int[5];

Q2

Given the following declarations :


int ival=2048;
int *iptr;
double *dptr;
Which of the following assignments ,if any , are illegal ?
Explain why ?
(a) ival = *iptr;

Q3

(b) *iptr = &ival

(c) *iptr = ival

(d) dptr = iptr

If ARR is an array of integers , why is the expression ARR++ is


not legal ?

Q4

Differentiate between Static and Dynamic allocation of memory.

Q5

What do you understand by memory leaks ? What are possible reasons for it ?
How can memory leaks be avoided?

Q6

What is this pointer ? What is it significance ?

38. Write a function which takes pointers to two strings as parameter and compare these
strings. The function should return 1 if two strings are same otherwise return 0.
Q7

How does the functioning of a function differ when


(i)
(ii)
(iii)

an object is passed by value


an object is passed by reference
an object is passed by pointer

Q8

Explain self referential structures with example .

Q9

What does this pointer do ? What are the application of this pointer ?

Q10

Define the string class having following member functions :


(a)
(b)
(c)
(d)
(e)

upcase( )
lowcase( )
length( )
scopy( )
sconcat( )

:
:
:
:

That converts the string into uppercase


:That convert the string to lowercase
That calculates the length of string
To copy the string
To concatenate two strings

JIT (JUST IN TEN MINUTES)


1.

Write a statement that displays the address of the variable testvar.


___________________________________________________________________________

2.

The contents of two pointers that point to adjacent variable of type float
differ by __________

3.

A pointer is

4.

1. an address of the variable


2. an indication of the variable to be accessed next
3. a variable of storing address
4. The data type of an address variable.
In a self referential structure

5.

1. each link contains a pointer to the next link


2. an array of pointers point to the links
3. each link contains data or pointer to data
4. the links are stored in an array
The new operator

6.

1. returns a pointer to a variable


2. creates a variable called new
3. obtains memory for a new variable
4. tells how much memory is available
The first element in a string is
1. The name of the string
2. The first character in the string
3. The length of the string

7.

4. the name of the array holding the string


The expression *test can be said to

8.

1.
2.
3.
4.
Using

The delete operator returns _____________________to the operating system.

10.

Given a pointer p that points to an object of type upperclass, write an

be a pointer to next
refer to the content of test
dereference test
refer to the value of the variable pointed to by test
new may result in less ___________________ memory than using an array.

expression that executes the exclu ( ) member function in this object.


___________________________________________________________________________
11.

Write a definition for an array numptrs of pointers to the strings One , two

and Three.
___________________________________________________________________________

12.

Using pointer notation write the prototype for a function called revstr( ) that
returns a string value and takes one argument that represents a string.
___________________________________________________________________________

13.

Using pointer notation write code that will transfer 80 characters from the
string s1 to the string s2.
___________________________________________________________________________

14.

Using pointer notation write a prototype declaration for a function called func
( ) that returns type void and takes a single argument that is an

array of type

char.
___________________________________________________________________________

15.

Of the three ways to pass arguments to functions , only passing by


_________________and passing

by __________________allow the function to

modify the argument in the calling program.

16.

If intarr is an array of intgers , why is the expreession intarr++ is not legal.


___________________________________________________________________________

17.

Write code using pointers to display the elements of the array intarr which
has 67 elements.

___________________________________________________________________________

18.

An address is a ________________ while pointer is a ____________________

19.

If a pointer testptr points to a variable testvar write a statement that


represents the content of testvar but does not use its name.
___________________________________________________________________________

20.

Write the definition for a variable of type pointer to float .


___________________________________________________________________________

Вам также может понравиться