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 time, 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
with any integer constant expression that evaluates to 0
, or with the nullptr
keyword.
Such a pointer is a null pointer and it does not point to any object.
For more information about the null pointer, see Null pointers.
The following examples define pointers with null pointer values:
char *a = 0;
char *b = NULL;
char *ch = nullptr;