Title: 11. POINTERS
111. POINTERS
2Pointer Variables
Each variable in a C program occupies space in
memory during its lifetime The address
of a variable is the address of its first byte in
memory. A pointer variable is a variable
capable of storing the address of (pointing to)
another variable.
3Pointer Variables
When a pointer variable is declared, its name
is preceded by an asterisk int p The
indicates that p is not an integer variable, but
rather a variable capable of pointing to an
integer. Each pointer variable can point only
to objects of a particular type int p /
points only to integers / float q / points
only to float values / char r / points only
to characters / Before it has been assigned a
value, a pointer points to nothing in particular.
4The Address Operator
A pointer can be given a value by assigning it
the address of a variable. To determine the
address of a variable, use the address operator
(represented by the symbol) int i, p p
i After this assignment, p points to i
5The Indirection Operator
To determine what a pointer currently points
to, use the indirection operator (represented by
the symbol) int i, p ... p
i printf("d\n", p) printf will display the
value of i.
6The Indirection Operator
If p points to i, then p is just another name
for i int i, p p i i
1 printf("d\n", i) / prints 1
/ printf("d\n", p) / prints 1 / p
2 printf("d\n", i) / prints 2
/ printf("d\n", p) / prints 2 /
7Pointer Assignment
One pointer may be assigned to another,
provided that both have the same type int i, p,
q p i q p After the assignment, both p
and q point to i Any number of pointers may
be pointing to the same variable.
8Pointer Assignment
Dont confuse pointer assignment with
assignment using the indirection operator int i,
j, p, q p i q j i 1 q p
9Pointers as Arguments
For a function to be able to modify a variable,
it must be given a pointer to the variable void
swap(int a, int b) int temp temp a a
b b temp swap(x, y) scanf is an
example of a function whose arguments must be
pointers scanf("dd", i, j)
10Using const to Protect Arguments
The const specifier provides a way to protect
arguments from change void f(const int p) int
j p 0 / illegal / p j / legal /
11Pointers as Return Values
Functions may return pointer values int
max(int a, int b) if (a gt b) return
a else return b p max(x, y) / p
points to either x or y /
12Pointers as Return Values
Warning Never return a pointer to a local
variable int f(void) int i ... return
i The variable i will not exist once f
returns, so the pointer to it will be invalid.