1.2 Declaring Pointers
Pointers must be declared before they can be used, just like a normal variable. The syntax of declaring a pointer is to place a
*
in front of the name. A pointer is associated with a type (such as int
and double
) too.type *ptr; // Declare a pointer variable called ptr as a pointer of type // or type* ptr; // or type * ptr; // I shall adopt this convention
For example,
int * iPtr; // Declare a pointer variable called iPtr pointing to an int (an int pointer) // It contains an address. That address holds an int value. double * dPtr; // Declare a double pointer
Take note that you need to place a
*
in front of each pointer variable, in other words, *
applies only to the name that followed. The *
in the declaration statement is not an operator, but indicates that the name followed is a pointer variable. For example,int *p1, *p2, i; // p1 and p2 are int pointers. i is an int int* p1, p2, i; // p1 is a int pointer, p2 and i are int int * p1, * p2, i; // p1 and p2 are int pointers, i is an int
Naming Convention of Pointers: Include a "
p
" or "ptr
" as prefix or suffix, e.g., iPtr
, numberPtr
, pNumber
, pStudent
.