Loading, please wait...

Definitions and Initialization

Pointers are variables whose values are memory addresses. Normally, a variable directly contains a specific value.

 

A pointer, on the other hand, contains an address of a variable that contains a specific value. In this sense, a variable name directly references a value, and a pointer indirectly references a value. Referencing a value through a pointer is called “indirection”.

 

 

 

 

Pointers, like all variables, must be defined before they can be used. The definition

int *countPtr, count;

specifies that variable countPtr is of type int * (i.e., a pointer to an integer) and is read, “countPtr is a pointer to int” or “countPtr points to an object of type int.” Also, the variable count is defined to be an int, not a pointer to an int. The * only applies to countPtr in the definition. When * is used in this manner in a definition, it indicates that the variable being defined is a pointer. Pointers can be defined to point to objects of any type.

 

The asterisk (*) notation used to declare pointer variables does not distribute to all variable names in a declaration. Each pointer must be declared with the * prefixed to the name; e.g., if you wish to declare xPtr and yPtr as int pointers, use int *xPtr, *yPtr;

 

Include the letters ptr in pointer variable names to make it clear that these variables are pointers and thus need to be handled appropriately.

 

Pointers should be initialized either when they’re defined or in an assignment statement.

 

A pointer may be initialized to NULL, 0 or an address. A pointer with the value NULL points to nothing. NULL is a symbolic constant defined in the <stddef.h> header (and several other headers, such as <stdio.h>). Initializing a pointer to 0 is equivalent to initializing a pointer to NULL, but NULL is preferred. When 0 is assigned, it’s first converted to a pointer of the appropriate type. The value 0 is the only integer value that can be assigned directly to a pointer variable. Initialize pointers to prevent unexpected results.