Page 239 - DCAP404 _Object Oriented Programming
P. 239
Object-oriented Programming
Notes 11.1 Understanding Pointers
Pointer is a variable which can hold the address of a memory location rather than the value at
the location. Consider the following statement:
int num = 84;
This statement instructs the system to reserve a 2-byte memory location and puts the value 84 in
that location. Assume that a system allocates memory location 1001 for num. Diagrammatically,
it can be shown as:
num Variable name
r
a
a
i
u
n
V
m
a
e
n
l
b
e
m
84
8 4 Value
u
e
l
V
a
Address of memory location
1 0 0 1 A d d r e s s o f m e m o r y l o c a t i o n
1001
As the memory addresses are numbers, they can be assigned to some other variable.
Let ptr be the variable which holds the address of variable num.
Thus, we can access the value of num by the variable ptr. Thus, we can say “ptr points to num”.
Diagrammatically, it can be shown as
u
m
num
n
num n u m
1001
84
8 4 1 0 0 1
2
0
1 0 0 1 2057
1001
5
7
Did u know? How does pointers helps us?
Pointers help in allocating memory dynamically. Pointers improve execution time and
saves space.
11.1.1 Pointer Variables
Pointers are variables that follow all the usual naming rules of regular, non-pointer variables.
As with regular variables, you must declare pointer variables before you use them. A type of
pointer exists for every data type in C++; you can use integer pointers, characters pointers,
floating-point pointers, floating-point pointer, and so on. You can declare global pointer or
local pointer, depending on where you declare them.
The only difference between pointer variables and regular variables is what they hold. Pointer
do not contain values, but the address of a value.
C++ has two operators:
1. & - The “address of” operator
2. * - The de-referencing operator
Whenever you see ‘&’ used with pointer, think of the phrase “address of”. The ‘&’ operator
provides the memory address of whatever variable it precedes. The * operator, when used with
232 LOVELY PROFESSIONAL UNIVERSITY