Node:Pointer types, Next:Pointers and initialization, Previous:Pointer operators, Up:Pointers
Pointers can point to any type of variable, but they must be declared to do so. A pointer to an integer is not the same type of variable as a pointer to a float or other variable type. At the "business end" of a pointer is usually a variable, and all variables have a type.
Here are some examples of different types of pointer:
int *my_integer_ptr; char *my_character_ptr; float *my_float_ptr; double *my_double_ptr;
However, GCC is fairly lenient about casting different types of pointer
to one another implicitly, or automatically, without your
intervention. For example, the following code will simply truncate the
value of *float_ptr
and print out 23. (As a bonus, pronunciation
is given for every significant line of the code in this example.)
#include <stdio.h> /* Include the standard input/output header in this program */ int main() /* Declare a function called main that returns an integer and takes no parameters */ { int *integer_ptr; /* Declare an integer pointer called integer_ptr */ float *float_ptr; /* Declare a floating-point pointer called float_ptr */ int my_int = 17; /* Declare an integer variable called my_int and assign it the value 17 */ float my_float = 23.5; /* Declare a floating-point variable called my_float and assign it the value 23.5 */ integer_ptr = &my_int; /* Assign the address of the integer variable my_int to the integer pointer variable integer_ptr */ float_ptr = &my_float; /* Assign the address of the floating-point variable my_float to the floating-point pointer variable float_ptr */ *integer_ptr = *float_ptr; /* Assign the contents of the location pointed to by the floating-point pointer variable float_ptr to the location pointed to by the integer pointer variable integer_ptr (the value assigned will be truncated) */ printf ("%d\n\n", *integer_ptr); /* Print the contents of the location pointed to by the integer pointer variable integer_ptr */ return 0; /* Return a value of 0, indicating successful execution, to the operating system */ }
There will still be times when you will want to convert one type of pointer into another. For example, GCC will give a warning if you try to pass float pointers to a function that accepts integer pointers. Not treating pointer types interchangeably will also help you understand your own code better.
To convert pointer types, use the cast operator. (See The cast operator.) As you know, the general form of the cast operator is as
follows:
(type) variable
Here is the general form of the cast operator for pointers:
(type *) pointer_variable
Here is an actual example:
int *my_integer_ptr; long *my_long_ptr; my_long_ptr = (long *) my_integer_ptr;
This copies the value of the pointer my_integer
to the pointer
my_long_ptr
. The cast operator ensures that the data types match.
(See Data structures, for more details on pointer casting.)