CHAPTER 11
POINTERS
Chapter Overview
11.1 Memory and References
11.2 Pointers
11.2.1 Pointer Declaration
11.2.2 The void! Pointer
11.23 Dereterence Operator
11.2.4 Pointer Initialization
11.3 Operations on Pointers
11.3.4 Pointer Addition
11.3.2 Pointer Subtraction
411.4 Pointers and Arrays
11.4.1 Accessing Array Elements with Pointers
11.5 Pointers and Strings
11.6 Array of Points
11.7 Pointers and Functions
1.8 Pointers and Structures
11.8.1 Passing Structure to Function using Pointers
11.8 Memnuty Management with Pointers
11.8.1 Dynamic Variables
11.9.2 The new Operator
11.9.3 The delete Operator
Programming Exercises
Exercise Questions
Multiple Choices
Fill in the Blanks
TruelFalse sig
—236 IT Series => Object-Oriented Programming using C++
11.1 Memory and References
Computer memory is a’ collection of different consecutive memory locations. These
‘meniory location are numbered sequentially. Fach variable is created at a unique location in
‘memory known as its address.
‘A program may declare many variables for different tasks. A variable declaration
reserves specific amount of space in memory for a particular variable. The variable name is
used to refer to that memory location, It allows the user to access a value in the memory. The
computer refers fo the memory using an address. A variable declaration associates following,
three attributes to a variable:
Variable name
* Variable type
* Variable memory address
‘The following statement declares an integer variable:
inta;
The name of variable is a and the type of variable is int. The address of the variable is
unknown. Computer creates the variable at any available location in the memory. The
memory address is a hexadecimal number that refers to a particular location in the memory.
The variable is éreated in the memory as follows:
oxon6afafo
int
=
The above box represents the memory location allocated for the variable a. ‘The
hexadecimal value above the box is its assumed address. The variable will occupy 2 bytes or
4 bytes in memory depending on the type of computer.
The actual address of the variable can be displayed by using reference operator &e. It is
also known as address operator. The reference operator is used to access the memory address
of a variable. The following statement will display the address of a’
coute<éa
Fae
How above Example Works?
The above program declares an integer variable n and initializes it to 10. The program
displays the value and address of n. ‘The address of operator is used to display the memory
address of n. The memory addresy may be different each time the program is executed,Chapter 11 = Pointers 337
11.2 Pointers
* Pointer a variable thatis used to store a memory address. The refereney operator is
used to.aecess the memory address of a variable and stare it in a pointer.
11.2.1 Pointer Declaration
The method of declaring a pointer is same as declaring a simple variable. An asterisk
'Sused in the declaration that indicates that the variable is a pointer variable.
Syntax
‘The syntax of declaring a pointer is as follows:
DataType ‘var,
DataType It is the type of variable pointed by the pointer variable.
bs W indicates that the variable is a pointer variable
var {tis the name of the pointer variable.
Example
int *p;
The above statement declares a pointer variable p. The data type int indicates that it
can store the memory address uf an integer variable. The data type of a pointer must be san.
«asthe data type of tNe variable whose memory address is to be stored in the pointer
{Us also possible to declare many pointer variables in one statement as follows
float “p1. *p2;
ne!
Write a program that inputs a number in an integer variable. It stores the address of the
‘ariable in a pointer and then displays the value and address of the variable.
#include
#include Output:
void main()
Enter an integer: 25
The value of n:
The address of n: Osifactttt
intn;
sot "ptr,
cout<<"Enter an integer *;
ina
ptr = 8
Cout<<"The value of n: "< Object-Oriented Programming using C++
‘The keyword 'void’is used as the data type of the pointer as follows
void “pj
The above statement declares a pointer variable p. The data type of the pointer is void.
Jtimeans that il can store the memory address of any type of variable,
#include
#include
Output:
Ha Dee ‘The value of n: 10
clrsor(); The address of n: Ox8i720ft4
intn = 10; The value of f: 25.18
The address of f: Ox8(724f10
‘The value of c: $
The address of c: Ox8172ffef
cout<<"The value of n: "<
#include
void main()
Output:
Enter an integer: 25
Enter an integer: 50
25+50=75
cltsor();
inta, b, s, *p1, *p2;
pt = 8a;
p2 = &b;
cout<<"Enter an integer: ";
cin>>*pt;
cout<<"Enter an integer: ";
cin>>*p2;
8= "pt + "2:Chapter 11 => Pointers 339
couts<*p1 <<" + "<
#tinclude
void main()
Output:
Enter an integer: 100
cirser(y, You entered 100
int
int *ptr = 8a},
cout<<"Enter an integer: *;
cin>>"ptr,
cout<<"You entered "<<"ptr;
} getch();
11.3 Operations on Pointers
The arithmetical operations on pointers work differently than normal ‘integer data
types. Only addition and subtraction operations can be performed on pointers. The effect of
both addition and subtraction depends on the size of the data type of the pointer.340 IT Series = Object-Oriented Programming using Cr+
11.3.1 Pointer Addition
‘The addition operation on pointer is used to move the pointer reference forward in the
memory, The change of memory address referenced by the pointer depends on the data type
of pointer. If the increment operator is used with an integer pointer, it will change the
reference by 2 bytes. If the increment operator is used with a character pointe, it will change
the reference by 1 bytes.
heer
Suppose there are three pointers as follows:
char *pChar;
short *pShort;
long *pLong;
Suppose the aboye pointers are pointing to the memory locations 1000, 2000 and 3000
respectively. The use of increment operator on the pointer will change the reference of the
pointers. The result of increment operator on each of the pointers is as follows:
00010011002
Figure 11.2: The result of increment operator on pointers
The above figure shows that the increment operator works differently on each pointer.
‘The type of pChar pointer is char. The increment operator moves the refernece of pChar by 1
byte. The type of pInt pointer is int. The increment operator moves the refernece of pint by 2
bytes. The type of pLong pointer is long, The increment operator moves the refernece of
pLong by 4 bytes.
11.3.2 Pointer Subtraction
‘The subtraction operation on pointer is used to move the pointer reference backward in
the memory. The change of memory address referenced by the pointer depends on the data
‘ype of pointer. If the decrement operator is used with an integer pointer, it will change the
reference by 2 bytes. If the decrement operator is used with a character pointer, it will change
the reference by 1 bytes.Chapter 11> Pointers 341
114 Pointers and Arrays
‘The pointers can also be used with arrays. An array is a collection of many élemens of
same type, All elements of the array are stored at consecutive memory locations. A pointer
an access all elements of an array if the address of first element is assigned to it. The name of
array represents the address of its first element. The address of first element can be assigned
to a pointer by assigning the name of the array to pointer. The pointer then can. access the.
vernaining elements as they are stored consecutively in the memory. t
‘The following example uses a pointer to access an array:
int Num[10];
int * ptr;
ptr = Num;
The first statement declares an array of integers Num with 20 elements. The second
statement declares a pointer variable ptr of type integer. The last statement assigns the
address of first element of Num to pointer ptr as follows:
3000 __3001__3002__3003__3004 30053006 3007 3008 3009
= LsteT a
pir
11.4.1 Accessing Array Elements with Pointers
‘The array elements can be accessed with pointers by moving the pointer to the desired
clement. The contents of an array elements can be accessed using dereference operator The
pointer reference can be moved forward and backward by using increment operator +4 and
decrement operators ~~,
‘The following example displays the values of first two array elements using pointer:
int Num{6} = {10, 20, 30, 40, 50};
int * ptr = Num;
cout<<*ptr;
pints;
cout<<*ptr;
The first line declares an array Num and initializes it with five values. The second
declares a pointer ptr and jnitializes it to the first element of the array Num. The third
statement displays the value of first element that is 10. The next statement increments the
pointer reference of the array. The pointer now refers to the second element. The last
statement then displays the value of second element that is 20.
The array elements can also be accessed without moving the pointer reference
permanently as follows:
coute<*ptr;
coute<"(ptr+4);
coute<"(ptr+2);a2 IT Series => Object-Oriented Programming using C++
The first statement displays the value of first element,as thé pointer refers to the first
clement of the array. The second statement displays the value of second element. The pointer
refers to the first element. The ‘ptr+1’ adds two bytes to that address resulting the address of
second element, Here, 1 represents one byte. Similarly, the last statement displays the value
of third element. Here, the value 2 represents two bytes. Two byles are added to the first
element of the array that results in the third element of the array.
Prog
‘Write a program to input five integers in an array and display them using a pointéf =
include
include Output:
void main() Enter five marks: 51
98
clrser(); 40
int marks[5), i; 26
intptr; 7A
CoS See ve TUsIne You entered the following values:
forte: IS Fe) 51 98 40 26 77
cin>>marks{i}
ptr = mark
cout<<"You entered the foliowing values:\n";
forli=0; i Output:
#include Enter five floating-point values: "|"
void main() a
clrser(); po
float arr}, “pt; S
inti: :
it 55
"I floatiig-poin ei .
fore Evie. STI ti he ceiac alas
cin>>arri; 55
ptr = &arr[4); 44
cout<<"The values in reverse order: in’; | 3.3
forli=0; i<6; i++) 22
cout<<*ptr--<
#include
void main() Output:
{ Enter your name: Muhammad Abdullah
etrser(); Your name is Muhammad Abdullah
char name(20}, “ptr;
cout<<"Enter your name: ";
cin. get(name, 20);
ptr = name;
cout<<"You name is “< Output:
feciude er
rey ‘The characteris found in the array.
clrser();
char str{] = "hello programming”;
char ch, *ptr, s;344 IT Series => Object-Oriented Programming using C++
s='n',
pir = str;
cout<<"Enter any character to find: *;
cin>>ch;
while(*pir++ != 0")
cout<<"The character is found in the array."<>a>>b>>o;
‘cout<<"You entered the following values:
for(i=0; i<3; i++)
cout<<*ptr[ij<
#include
Void exchange(int
Output:
ie a Enter two integers: 10 20
elrecr(); Values before swapping:
int nt, n2; 0.
cout<<"Enter two integers: *; b=20
cin>>ni>>n2; Values after swapping:
‘cout<<"Values before swapping: \n";
cout<<'nt = "<>"x,
}
et dbi(int *y)
y="y*2;
}
How above Program Works?
‘The above program declares an integer variable num and two functions. It passes the
variable to both function using pointers. The first function inputs the value and second
function doubles its value. The formal parameters of both functions actually refer to the same
memory address of the variable num.
num
e
* y
11.8 Pointers and Structures
The pointers can refer to a structure variable in the same way as simple variables.
However, the dot operator is not used to access the members of a structure when pointers are
used to refer to a structure variable. The selection operator -> is used instead of dot operator
to access the structure member. It consists of minus sign and greater than sign.
Write a program that declares a structure to store the record of a book. It defines a
structure variable, inputs the values and displays them using pointer.
‘#include
#include
‘struct Book
{
char author[30);
int pages;
int price;
;
Void main()
cirser();
Book rec, *Chapter 11 > Pointers 2 347
pir = &reo;
cout<<"Enter author name: "; eee
cin. get(ptr->author, 30); Enter author name: Haroon Yahya
cout<<"Enter pages: *; Enter pages: 490
cin>>ptr->pages; Enter price: 350
cout<<"Enter price: Author: Haroon Yahya
cin>>ptr->price; Pages: 490
cout<<"Author: "<author<pages<price<
#include
struct Student Output:
{ Enter roll no: 10
int rno, marks; Enter marks: 922
; float gpa; Enter gpa: 3.55
Void input(Student*); —
void output(Student’ CEAaEE
void main()
}
Void input(Student *p)
{
cout<<"Enter roll no: ";
cin>>p->mo;
cout<<"Enter marks: ";
cin>>p->marks;
cout<<"Enter gpa: *;
cin>>p->gpa;
}
ee output(Student *m)
cout<<"Roll no: "<rno<marks<gpa< Object-Oriented Programming using C++
How above Program Works?
The above program) declares a structure variable s and two functions. It passes the
variable to both funetion using pointers. The first function inputs the record and. second
function, displays it, The formal parameters of both functions actually refer to the same
memory address of the variable s,
te
Write a program that decalres a structure to store hours, minutes and’ seconds. It
declares a structure variable. It inputs number of seconds from the user and passes seconds
to function by value and structure variable using pointer. The function converts the seconds
into hours, minutes and seconds and stores it in the structure variable. The main() function
finally displays the time on screen.
‘#include
‘#include
siuctime Output:
{ Enter total number of seconds: 5300
int nours; Hours: 1
int minutes; Minutes: 28
int seconds; Seconds: 20
}timet;
void main()
long sec;
clrser();
void convert(time*, long);
cout<<"Enter total number of seconds: ";
cin>>sec; .
convert(&time1,sec);
cout<<"\inThe time in hh mm ss format is:";
‘cout<<"\nHours: "<seconds = sec % 60;
long x = sec/60;
temp->minutes = x % 60;
temp->hours = x/ 60;
}Chapter 11 => Pointeis : 349
11.9 Memory Management with Pointers
Global name space: It is used to store global variables.
Registers: These are special memory units built into CPU.
Code space: It contains the program code.
Stack It contains local variables and function parameters, It is also called static
memory.
A variable that is created during program execution is called dynamic variable. The
dynamic variables can be creatéd in C++ using pointers: C++ provides two operators new
and delete operators for dynamic variables, The new operator is used to ereate dynamic
variables and delete operator is used to delete dynamic variables during program execution.
11.9.2 The new Operator
‘The new operator is used to allocate memory dynamically. It is followed by)the type of
object for which the memory is to be allocated: The compiler allocates the amount of memory
according to the type of object. The new operator retums a memorysaddress, The returned
address must be assigned to a pointer. The pointer is then used to access the memory lecation
and process tie values stored in that address. The new operator can be used to create simple
variable, an object or an array of objects.
Syntax
The following syntax is used to create one variable:
new Datatype;
The following syntax is used to create an array dynamically: perce
new Datatypefiength];
int *ptr;
pir = new int;
The first statement declares an integer pointer variable. The second statement uses the
srg eeralor to create an integer variable in the memory dynamically. The address of the
allocated memory is stored in the pointer ptr,
C-}+—4
=e
Jae Above figure shows that the newly created memory has no name. It can only be
accessed using the pointer.
int *ptr;
ptr = new int{S];350 IT Series => Object-Oriented Programming using C++
The first statement declares an integer pointer variable, The second statement uses the
new operator to create an array of integers in the memory dynamically. The address of first
element of the artay is stored in the pointer ptr.
‘ptr
11.9.3 The delete Operator
The delete operator deallocates the memory and returns the allocated memory back to
the free store. It takes a pointer as parameter and releases the memory referred by the
poittter. The dynamically created object should be deleted when it is nor more required.
‘The pointer declared in a function is treated as a local variable. The pointer goes out of
scope and is lost when the control exists from the function:in which the pointer is declared.
However, the memory allocated with new operator is not freed automatically, That memory
becomes unavailable. This situation is known as memory leak. This memory canot be
recovered until the program ends.
Syntax
The following syntax is used to delete one variable dynamically:
delete variable;
‘The following syntax is used to delete an array dynamically:
deletel] variable;
Ea
delete ptr,
The above statement will deallocate the memory referred by the pointer ptr. The use of
delete operator is slightly different when it refers to an array. The following statement is used
if the pointer ptr refers to an array:
delete 0) ptr;
Write a program that uses new operator to create an integer, inputs value in it and then
displays that value.
include
#include Output:
void main() Enter an integer: 50
{ ‘You entered 50
Tt is stored at Ox8fad0ede
ptr
‘cout<<"Enter an integer: *;
cin>>*ptr,
cout<<"You entered "<<*ptr<