CSI2131 Pointers
Each byte of memory has a different address.
Each variable is stored
in some number of contiguous bytes of memory.
The address of a variable
is the address of the first byte in which
it's stored.
0100
0101
xxx <-- An integer might take 4 bytes.
This integer's
0102
xxx address is 0101
0103
xxx
0104
xxx
0105
0106
0107
ccc <-- A character only takes one byte.
This character's
0108
address is 0107
In C/C++, a pointer is
a variable that stores an address. If a
pointer 'p' contains
the address of a variable 'x', we say p points
to x. This is
typically drawn with an arrow from p to x:
p x
+---+
+---+
| O |
--> | 5 |
+-+-+
/ +---+
| |
+----+
Each pointer can point
to many different variables at different times
during the program execution,
but each variable must be of the same
type.
Declarations
The following declares
integers 'a' and 'b' and a "pointer to integer"
'p'. The asterisk
before 'p' shows that it is a pointer. There can
be a space between the
asterisk and 'p' if you wish.
int
a, b;
int
*p;
"Address of''
To get 'p' pointing to 'a', we assign 'p' the address of 'a':
p = &a;
The ampersand, when appearing
in front of a variable, gives that
variable's address.
The above statement is read 'p is assigned the
address of a'.
Dereferencing
To assign a value to
the variable pointed to by 'p', we use the
asterisk.
*p
= 55;
cout
<< a << *p;
output ---> 55 55
The above statement is
read 'the integer pointed to by p is assigned
55'. This operation
''dereferences'' p. In other words, p is a
''reference'' to something
and *p is the actual something.
To get the value, we also use the asterisk:
b
= *p;
cout
<< b;
output ---> 55
Layout in memory
Suppose things are laid out in memory as follows:
0100
aaa < -- integer a
0101
aaa
0102
aaa
0103
aaa
0104
bbb < -- integer b
0105
bbb
0106
bbb
0107
bbb
0108
0109
010A
010B
010C
ppp < -- pointer p
010D
ppp
010E
ppp
010F
ppp
Then after the following
statements, memory would look as shown below
(the hyphens are placeholder
for the remainder of the variable).
a
= 55;
p
= &a;
b
= *p + 22;
0100
55 < -- integer a
0101
-
0102
-
0103
-
0104
77 < -- integer b
0105
-
0106
-
0107
-
0108
0109
010A
010B
010C
0100 < -- pointer p
010D
-
010E
-
010F
-
Pointers and classes
C++ pointers can also be defined to point to class objects:
Myclass
m;
Myclass
*p;
p
= &m; // "&" here
is the address of m
The following then, are the same (call the method "print" in Myclass)
m.print();
(*p).print();
p->print();