Initialization of pointers
The initializer is an
= (equal sign) followed by the
expression that represents the address that the pointer is to contain.
The following example defines the variables time and speed as
having type double and amount as having type
pointer to a double. The pointer amount is initialized
to point to total:
double total, speed, *amount = &total;The compiler converts an unsubscripted array name to a pointer
to the first element in the array. You can assign the address of the
first element of an array to a pointer by specifying the name of the
array. The following two sets of definitions are equivalent. Both
define the pointer
student and initialize student to
the address of the first element in section:
int section[80];
int *student = section;is equivalent to:
int section[80];
int *student = §ion[0];You can assign the address of the first character in a string constant
to a pointer by specifying the string constant in the initializer.
The following example defines the pointer variable
string and
the string constant "abcd". The pointer string is
initialized to point to the character a in the string "abcd".
char *string = "abcd";The following example defines
weekdays as an array of
pointers to string constants. Each element points to a different string.
The pointer weekdays[2], for example, points
to the string "Tuesday".
static char *weekdays[ ] =
{
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
};A pointer can also be initialized to null using any integer constant expression that evaluates to
0, for example char * a=0;
Or with the
nullptr keyword. Such a pointer is a null pointer. It does not point to
any object.
The following examples define pointers with null pointer values:
char *a = 0;
char *b = NULL;
Beginning of C++11 only.
char *ch = nullptr;
End of C++11 only.
Related information