Chapter 05 Compound Data Type - Constructed Type
5. Pointer Type - Description of Address in Memory
Pointer Type is a user-defined data type used to describe addresses in the memory. As has been introduced before, we can call anything in the program either by its name or by its address, and pointer type is how we describe the address.
5.1 Definition and Initialization of A Pointer
<base-type> *<pointer-variable>;
Here
*
is a symbol that indicates that the variable here is a pointer type.The base type of a pointer tells what kind of data this pointer can point to.
If the base type of a pointer is
void
, it is a general pointer and can point to any data type.A pointer is also a kind of data, so it needs a room in the memory too, which also means that a pointer itself can be pointed to by another pointer.
<base-type> *<pointer> = &<variable>;
<base-type> *<pointer> = <another-pointer>;
Operator
&
gets the address of a variable and we can assign it to a pointer type whose base type is the type of this variable.Or we can just use another pointer with the same base type to do the initialization.
On the other hand, there exists an operator
*
which can get the value stored in an address.We use the symbolic constant
NULL
to represent an empty pointer, which is the macro of 0 and can represent any type of pointer that is empty.
5.2 Manipulation for Pointer Type
-
Assignment
<pointer> = <another-pointer>;
A pointer can be assigned to another pointer if it is NULL or if they share the same base type.
<pointer> = &<variable>;
Put the address of the variable into the pointer.
-
Access
*<pointer>
The expression above evaluates to the value in the address that the pointer points to.
If the pointer points to a structure type, we can use the following two ways to point to its members.
(*<pointer>).<member> //or <pointer>-><member> //the two ways above are exactly the same
-
Computing
<pointer>[<integral-expression>] <=> *(<pointer> + <integral-expression>) <pointer> + <integer> = <address> + <integer> * sizeof(<base-type>)
When we use a pointer to add or minus an integer, it means to move the pointer several rooms forward or backward, and the size of the room depends on its base type.
<pointer1> - <pointer2> = (<address1> - <address2>) / sizeof(<base-type>)
The offset of two pointer describes how many rooms are there between the places these two pointers point to.
And if we compare two pointer, we compare their offset with zero.
-
Output
If we output a pointer, we output the address it points to except the pointer of a character array, in which case we output the whole string.
If you want to output the value, use the
*
operator.If you want to output the address a character pointer points to, use explicit type conversion.
A pointer can also play the role of parameter or return value. If a pointer is passed to a function as an argument, the function is call by reference, which means it could have side effects.