Lecture Notes for Introduction to Computer Science II
2 August 2001 - Pointer Declarations and Basic Operations
- pointer declarations
- the declaration
T * t_ptr;
declares a variable of type pointer to
T
- the
*
applies only to the following variable name
- convention dictates that pointer variables have names that indicate
they're pointers -
_ptr
, ptr
, or p
- always initialize pointer variables - a real value or 0; avoid the
dreaded
NULL
- two pointer types T1
*
and T2*
are equal if
T1 and T2 are the same
-
i = c
is ok; ip = cp
is illegal
- ints are required to be assignable to pointers, however, it's not
required that the assignment make sense
- basic pointer operations - address of and follow pointer
- the address-of operator
&
- unary prefix operator
&
var returns the address of var
- if var has type T,
&
var is a value of type
pointer to T
- can only apply
&
to variables - &1
is illegal
- the follow-pointer operator
*
; also indirection or dereferencing
operator
- unary prefix operator
*(
expr)
returns the value at
the location pointed to by expr
- expr is often a pointer variable, but not always
- if expr has type T
*
, *(
expr)
is a
value of type T
- the pointer-follow operator will follow whatever the expression tells
it to, even garbage
This page last modified on 1 August 2001.