COMP2012 Object-Oriented Programming and Data Structures
Revision: Pointers
Dr. Desmond Tsoi
Department of Computer Science & Engineering
The Hong Kong University of Science and Technology
Hong Kong SAR, China
Rm 3553, [email protected]
COMP2012 (Fall 2018)
1 / 47


Declaration of Pointer Variables
If a variable is going to hold an
address of another variable
, it must
be declared as follows:
Actually, we can treat
<
type
>
*
as a
special type
which is pointer
type
Rm 3553, [email protected]
COMP2012 (Fall 2018)
3 / 47

Recall the syntax for declaring a pointer variable:<type>*<variable name>;Examples:// Declare a pointer that points to a variable of integer typeint*a;// the value of a is garbage but is not NULL
double*b;// the value of b is garbage but is not NULL
char*c;// the value of b is garbage but is not NULL
*
close to type OR
// close to name
int
*
d;
// the value of d is garbage but is not NULL
int
*
d;
// same as above, no difference
We will talk a bit more about NULL pointer later!
Rm 3553, [email protected]
COMP2012 (Fall 2018)
4 / 47

Pointer Operator & (Address-Of)
There are
two
operators associated with pointers. They are & and *
(Note: The * here
doesn’t mean multiplication
)
The first operator,
&
is a unary operator (i.e. with single operand)
that returns the
memory address of
another variable
I
Usage:
&
<
variable name
>
We can think of & as returning ”the address of”
int
var1 = 5;
// pint receives the address of var1
int
*
pint = &var1;
double
var2 = 1.23;
// pdouble receives the address of var2
double
*
pdouble = &var2;
Rm 3553, [email protected]
COMP2012 (Fall 2018)
5 / 47

Pointer Operator & (Address-Of)(Cont’d)
Graphical representation of last example
Rm 3553, [email protected]
COMP2012 (Fall 2018)
6 / 47

Example - & (Address-Of)
#include
<
iostream
>
using namespace
std;
int
main()
{
int
a, b;
a = 88;
b = 100;
cout
"The address of a is "
&a
endl;
cout
"The address of b is "
&b
endl;
return
0;
}
Output:
The address of a is 0x22ff74
The address of b is 0x22ff70
Rm 3553, [email protected]
COMP2012 (Fall 2018)
7 / 47


The Different Uses of Operator *
Do not confuse the use of operator * in
declaring a pointer variable versus the use
of * as the dereference operator
Example
// This means to declare a pointer variable
//
*
that sticks with a data type refers
// to a pointer variable declaration
int
*
p;
int
i, j = 10;
int
*
p = &j;
// This means to dereference the variable p
//
*
that sticks with a pointer variable
// refers to dereference
i =
*
p;
Rm 3553, [email protected]
COMP2012 (Fall 2018)
9 / 47
