Pointers and Pointer Operations
A pointer is just a variable which stores an address.
Besides holding an address rather than data (arguably, an address is data of a sort)
pointers differ from other variables in that they point to data of a specific type.
The size of a pointer is determined by the operating system and the C compiler.
All pointers in any given OS are the same size.
The operations you can perform on a pointer are restricted to five:
- Assignment - We can assign an address to a pointer variable.
To do this you can use an array name, the address of operator(&),
or a return value from a function that returns an address (such as strchr()).
- Value-finding (dereferencing) - The * operator gives us the
value stored in the pointed-to location in memory. The value is dependent
on the type of the data pointed to.
- Increment-decrement a pointer - We can increment a pointer by using
regular addition or by using the increment operator.
Incrementing a pointer to an array element instructs it to point to the next
element of the array. In general, incrementing a pointer changes the address
stored in the pointer so that it points to the next object of the type
the pointer points to. For example, if you increment a pointer to a double
eight bytes is added to the address in the pointer.
All pointers are not created equal.
Note that incrementing has no effect on the address of the pointer, which is fixed.
It changes the address stored in the pointer.
We can decrement a pointer also, of course.
- Differencing - We can find the difference between tow pointers.
The result of differencing two pointers results in a value equal to the number
of objects between the two addresses, not the number of bytes between
the addresses (unless the objects happen to be one byte in size). Therefore
differencing two pointers to int will yield the number of int
variables that can be between the two addresses.
Caution: C does not keep track of whether a pointer points to
memory containing the data type that the pointer is supposed to point to.
Also, C does not require that a pointer be set to point to a
real memory address. This is your responsibility as the programmer.
A runaway pointer is a dangerous thing. In some operating systems you can
get protection faults. In other operating systems you could trash the
operating system itself.
When used properly and carefully, pointers can be used to do powerful things in C.
When used carelessly, pointers can cause problems that take a long time to find and correct.