Topics covered on Wednesday, 2010-08-18
Pointers
Variable attributes
- Each variable has 3 attributes associated with it:
- Its type (e.g.
int, char, etc.)
- Its value (e.g.
10, 'a', etc.)
- Its address (location in memory).
Getting the Address of a Variable
Given a variable
var
use the construct
&var
to get its address.
&var is termed a
reference to
var.
Pointer Variables
A pointer variable is a special variable that can hold the address of another variable. To declare a pointer variable
pi which can hold the address of an
int variable, use the construct:
int *pi;
Then you can assign the address of another variable (say
var) to
pi like:
pi = &var;
Using a Pointer
You can use a pointer variable by itself, or by
dereferencing it.
Example 1: Using a pointer by itself
int i;
int *p1;
int *p2;
p1 = &i; // Now p1 contains the address of i
p2 = p1; // Now p2 also contains the address of i
As you can see, pointers may also be treated like other variables; they may be assigned to, and their value retrieved.
Example 2: Dereferencing a pointer
int i = 10; // i now has the value 10
int *p1;
p1 = &i; // p1 now contains the address of i
(*p1) = 20; // Whatever variable p1 had the address of now contains 20
cout << i << endl; // Prints 20
Pointer Arithmetic
Adding to and subtracting from a pointer changes the value by the size of the item pointed to. If an
int is 4 bytes and
pi is a pointer to
int, then:
pi = 200;
will set the value of
pi to 200. Then if you do:
pi = pi + 1;
pi will now contain the address of the next
int in memory, i.e. 204.
Arrays and Pointers
An array definition stores contiguous space for a number of variables of a given type. E.g.
int a[4]; will reserve space for 4 variables of type
int, called
a[0],
a[1],
a[2] and
a[3].
The array name without a subscript,
a is a special case.
a by itself refers to the address of the first element of the array, and is of type pointer to int.
In other words,
a == &a[0]
a can be used like any other pointer to int. However,
a is a
constant, not a
variable.
Further Reading
http://www.cplusplus.com/doc/tutorial/pointers/ contains a reasonable tutorial on pointers in C++.