A pointer is memory address.
C is all about memory and its direct addressing and manipulation.
This orientation has made the language very effective in writing low-level code for device drivers and operating systems. That strength comes at a price, though.
On most modern 32-bit machines, a pointer is implemented as a 32-bit integer, and on 64-bit machines, as a 64-bit integer.
Pointers are so fundamental to C, very little can be done without them. Pointers are the only way to pass references to data, and are the usual way to represent arrays and strings. Even functions are pointers in C.
- The only way a function can modify something via an argument is by way of a pointer argument (which itself is just a number, passed by value). Here is a more complete practical example.
-
declaring a pointer
type *name;
note this only says that
name
is a variable that holds a pointer to atype
, but not what it points to. (In fact, the above un-initialized declaration results inname
holding a trash integer.) -
the address-of operator “
&
” gets the address of something in memory; this can be assigned to a pointer:int theInt = 3; int *theIntPointer = &theInt;
-
one de-references the pointer to access what it points to using the de-reference operator (which is also the asterisk, rather confusingly)
int theInt = 3; int *theIntPointer = &theInt; *theIntPointer = 4; /* now theInt has the value 4 */
-
Attempts to access memory that hasn’t been properly allocated, such as by using an uninitialized pointer, is the cause of a whole class of bugs in C. On Unix-like systems, this will usually cause a segmentation fault.
pointer arithmetic
When an integer is added to a pointer, the value of the pointer is increased not by the value of the integer, but my the integer times the size of the object pointed to, to effectively offset the pointer to address another object in an array.
int myInts[10]; *myInts = 3; /* these two are equivalent */ myInts[0] = 3; *(myInts + 2) = 5; /* these two are equivalent */ myInts[2] = 5; int *ii; for( ii = myInts; ii < myInts + 10; ii++ ){ *ii = 7; } /* sets each element of myInts to 7 */
function pointers
The machine code of a function is also data that lies in memory. The entry point of a function thus also has an address; that address can be used as a pointer to the function.
C has special syntax for function pointers.
Function pointers make possible many advanced techniques, including modular programming.
- algorithm with replaceable functionality
- list of actions
- data with attached function (a method of a module)
Define a type for certain kind of function
typedef (return_type)function_type_name( arg1_type arg1 name ...)
constness
To indicate to the user of your function whether or not the function
will alter the data pointed to by an argument, use the
const
modifier.
(Not strictly enforced by most compilers though.)