A pointer is a value that designates the address (i.e., the location in memory), of some value. Pointers are variables that hold a memory location.
There are four fundamental things you need to know about pointers:
- How to declare them (with the address operator '': )
- How to assign to them ()
- How to reference the value to which the pointer points (known as dereferencing, by using the dereferencing operator '': )
- How they relate to arrays (the vast majority of arrays in C are simple lists, also called "1 dimensional arrays", but we will briefly cover multi-dimensional arrays with some pointers in a later chapter).
Pointers can reference any data type, even functions. We'll also discuss the relationship of pointers with text strings and the more advanced concept of function pointers.
Consider the following snippet of code which declares two pointers:
Lines 1-4 define a structure. Line 8 declares a variable which points to an , and line 9 declares a variable which points to something with structure MyStruct. So to declare a variable as something which points to some type, rather than contains some type, the asterisk () is placed before the variable name.
In the following, line 1 declares as a pointer to a long and as a long and not a pointer to a long. In line 2, is declared as a pointer to a pointer to an int.
Pointer types are often used as parameters to function calls. The following shows how to declare a function which uses a pointer as an argument. Since C passes function arguments by value, in order to allow a function to modify a value from the calling routine, a pointer to the value must be passed. Pointers to structures are also used as function arguments even when nothing in the struct will be modified in the function. This is done to avoid copying the complete contents of the structure onto the stack. More about pointers as function arguments later.
Assigning values to pointers
So far we've discussed how to declare pointers. The process of assigning values to pointers is next. To assign the address of a variable to a pointer, the or 'address of' operator is used.
Here, pPointer will now reference myInt and pKeyboard will reference dvorak.
Pointers can also be assigned to reference dynamically allocated memory. The malloc() and calloc() functions are often used to do this.
The malloc function returns a pointer to dynamically allocated memory (or NULL if unsuccessful). The size of this memory will be appropriately sized to contain the MyStruct structure.
The following is an example showing one pointer being assigned to another and of a pointer being assigned a return value from a function.
When returning a pointer from a function, do not return a pointer that points to a value that is local to the function or that is a pointer to a function argument. Pointers to local variables become invalid when the function exits. In the above function, the value returned points to a static variable. Returning a pointer to dynamically allocated memory is also valid.
To access a value to which a pointer points, the operator is used. Another operator, the operator is used in conjunction with pointers to structures. Here's a short example.
The expression is entirely equivalent to . They both access the element of the structure pointed to by . There is one more way of dereferencing a pointer, which will be discussed in the following section.
When dereferencing a pointer that points to an invalid memory location, an error often occurs which results in the program terminating. The error is often reported as a segmentation error. A common cause of this is failure to initialize a pointer before trying to dereference it.
C is known for giving you just enough rope to hang yourself, and pointer dereferencing is a prime example. You are quite free to write code that accesses memory outside that which you have explicitly requested from the system. And many times, that memory may appear as available to your program due to the vagaries of system memory allocation. However, even if 99 executions allow your program to run without fault, that 100th execution may be the time when your "memory pilfering" is caught by the system and the program fails. Be careful to ensure that your pointer offsets are within the bounds of allocated memory!
The declaration is used to declare a pointer of some nonspecified type. You can assign a value to a void pointer, but you must cast the variable to point to some specified type before you can dereference it. Pointer arithmetic is also not valid with pointers.
Pointers and Arrays
Up to now, we've carefully been avoiding discussing arrays in the context of pointers. The interaction of pointers and arrays can be confusing but here are two fundamental statements about it:
- A variable declared as an array of some type acts as a pointer to that type. When used by itself, it points to the first element of the array.
- A pointer can be indexed like an array name.
The first case often is seen to occur when an array is passed as an argument to a function. The function declares the parameter as a pointer, but the actual argument may be the name of an array. The second case often occurs when accessing dynamically allocated memory. Let's look at examples of each. In the following code, the call to calloc() effectively allocates an array of struct MyStruct items.
Pointers and array names can pretty much be used interchangeably. There are exceptions. You cannot assign a new pointer value to an array name. The array name will always point to the first element of the array. In the function above, you could however assign a new value to parm1, as it is just a pointer to the first element of myArray. It is also valid for a function to return a pointer to one of the array elements from an array passed as an argument to a function. A function should never return a pointer to a local variable, even though the compiler will probably not complain.
When declaring parameters to functions, declaring an array variable without a size is equivalent to declaring a pointer. Often this is done to emphasize the fact that the pointer variable will be used in a manner equivalent to an array.
Now we're ready to discuss pointer arithmetic. You can add and subtract integer values to/from pointers. If myArray is declared to be some type of array, the expression , where j is an integer, is equivalent to . So for instance in the above example where we had the expression secondArray[i].num2, we could have written that as or more simply .
Note that for addition and subtraction of integers and pointers, the value of the pointer is not adjusted by the integer amount, but is adjusted by the amount multiplied by the size (in bytes) of the type to which the pointer refers. One pointer may also be subtracted from another, provided they point to elements of the same array (or the position just beyond the end of the array). If you have a pointer that points to an element of an array, the index of the element is the result when the array name is subtracted from the pointer. Here's an example.
You may be wondering how pointers and multidimensional arrays interact. Let's look at this a bit in detail. Suppose A is declared as a two dimensional array of floats () and that pf is declared a pointer to a float. If pf is initialized to point to A, then *(pf+1) is equivalent to A and *(pf+D2) is equivalent to A. The elements of the array are stored in row-major order.
Let's look at a slightly different problem. We want to have a two dimensional array, but we don't need to have all the rows the same length. What we do is declare an array of pointers. The second line below declares A as an array of pointers. Each pointer points to a float. Here's some applicable code:
We also note here something curious about array indexing. Suppose myArray is an array and idx is an integer value. The expression myArray[idx] is equivalent to idx[myArray]. The first is equivalent to *(myArray+idx), and the second is equivalent to *(idx+myArray). These turn out to be the same, since the addition is commutative.
Pointers can be used with preincrement or post decrement, which is sometimes done within a loop, as in the following example. The increment and decrement applies to the pointer, not to the object to which the pointer refers. In other words, *pArray++ is equivalent to *(pArray++).
Pointers in Function Arguments
Often we need to invoke a function with an argument that is itself a pointer. In many instances, the variable is itself a parameter for the current function and may be a pointer to some type of structure. The ampersand character is not needed in this circumstance to obtain a pointer value, as the variable is itself a pointer. In the example below, the variable , a pointer, is a parameter to function , and is passed as an argument to . The second parameter to is an int. Since in function , is a pointer to an int, the pointer must first be dereferenced using the * operator, hence the second argument in the call is . The third parameter to function is a pointer to a long. Since is itself a pointer to a long, no ampersand is needed when it is used as the third argument to the function.
Pointers and Text Strings
Historically, text strings in C have been implemented as arrays of characters, with the last byte in the string being a zero, or the null character '\0'. Most C implementations come with a standard library of functions for manipulating strings. Many of the more commonly used functions expect the strings to be null terminated strings of characters. To use these functions requires the inclusion of the standard C header file "string.h".
A statically declared, initialized string would look similar to the following:
The variable can be viewed as an array of 21 characters. There is an implied null character ('\0') tacked on to the end of the string after the 'd' as the 21st item in the array. You can also initialize the individual characters of the array as follows:
An initialized array of strings would typically be done as follows:
The initialization of an especially long string can be split across lines of source code as follows.
The library functions that are used with strings are discussed in a later chapter.
Pointers to Functions
C also allows you to create pointers to functions. Pointers to functions can get rather messy. Declaring a typedef to a function pointer generally clarifies the code. Here's an example that uses a function pointer, and a void * pointer to implement what's known as a callback. The function invokes a caller supplied function with caller data. Note that really doesn't know anything about what refers to.
Some versions of C may not require an ampersand preceding the argument in the call. Some implementations may require specifically casting the argument to the type, even though the function signature exacly matches that of the typedef.
Function pointers can be useful for implementing a form of polymorphism in C. First one declares a structure having as elements function pointers for the various operations to that can be specified polymorphically. A second base object structure containing a pointer to the previous structure is also declared. A class is defined by extending the second structure with the data specific for the class, and static variable of the type of the first structure, containing the addresses of the functions that are associated with the class. This type of polymorphism is used in the standard library when file I/O functions are called.
A similar mechanism can also be used for implementing a state machine in C. A structure is defined which contains function pointers for handling events that may occur within state, and for functions to be invoked upon entry to and exit from the state. An instance of this structure corresponds to a state. Each state is initialized with pointers to functions appropriate for the state. The current state of the state machine is in effect a pointer to one of these states. Changing the value of the current state pointer effectively changes the current state. When some event occurs, the appropriate function is called through a function pointer in the current state.
Practical use of function pointers in C
Function pointers are mainly used to reduce the complexity of switch statement. Example with switch statement:
Without using a switch statement:
Function pointers may be used to create a struct member function:
Use to implement this pointer (following code must be placed in library).
Examples of pointer constructs
Below are some example constructs which may aid in creating your pointer.
The sizeof operator is often used to refer to the size of a static array declared earlier in the same function.
To find the end of an array (example from wikipedia:Buffer overflow):
To iterate over every element of an array, use
Note that the operator only works on things defined earlier in the same function. The compiler replaces it with some fixed constant number. In this case, the was declared as an array of 10 char's earlier in the same function, and the compiler replaces with the number 10 at compile time (equivalent to us hard-coding 10 into the code in place of ). The information about the length of is not actually stored anywhere in memory (unless we keep track of it separately) and cannot be programmatically obtained at run time from the array/pointer itself.
Often a function needs to know the size of an array it was given -- an array defined in some other function. For example,
Unfortunately, (in C and C++) the length of the array cannot be obtained from an array passed in at run time, because (as mentioned above) the size of an array is not stored anywhere. The compiler always replaces sizeof with a constant. This sum() routine needs to handle more than just one constant length of an array.
There are some common ways to work around this fact:
- Write the function to require, for each array parameter, a "length" parameter (which has type "size_t"). (Typically we use sizeof at the point where this function is called).
- Use of a convention, such as a null-terminated string to mark the end of the array.
- Instead of passing raw arrays, pass a structure that includes the length of the array (such as ".length") as well as the array (or a pointer to the first element); similar to the or classes in C++.
It's worth mentioning that sizeof operator has two variations: (for instance: or ) and (for instance: or ).
Previous:14.2 Dynamic Memory Allocation
Up:14 Storage Class and Scope
Previous Page:14.2.2 Dynamic Arrays
Next Page:14.3.1 Function Pointers as Returned Values
14.3 Pointers to Functions
We saw earlier that functions have a storage class and scope, similar to variables. In C, it is also possible to define and use function pointers, i.e. pointer variables which point to functions. Function pointers can be declared, assigned values and then used to access the functions they point to. Function pointers are declared as follows:Here, is declared as a pointer to a function that returns type, and is a pointer to a function that returns . The interpretation is as follows for the first declaration: the dereferenced value of , i.e. followed by indicates a function, which returns integer type. The parentheses are essential in the declarations. The declaration without the parentheses: declares a function that returns an integer pointer.
We can assign values to function pointer variables by making use of the fact that, in C, the name of a function, used in an expression by itself, is a pointer to that function. For example, if and are declared as follows:the names of these functions, and , are pointers to those functions. We can assign them to pointer variables:
The functions can now be accessed, i.e. called, by dereferencing the function pointers:
Function pointers can be passed as parameters in function calls and can be returned as function values. Use of function pointers as parameters makes for flexible functions and programs. An example will illustrate the approach. Suppose we wish to sum integers in a specified range from x to y. We can easily implement a function to do so:The file contains prototypes for all the functions written in . Next, suppose we wish to sum squares of integers from x to y. We must write another function to do so: Function returns the integer square of . The constructions of the two functions and are identical. In both cases, we cumulatively add either the integers themselves or squares of the integers. A function , which returns the value of the integer argument, can be used in to make the functions truly identical. Here is a modified function that uses : The two sum functions, and , are now identical except for the functions used in the cumulative sum expressions. In one case, we use , in the other case, . It is clear that a single more flexible generic sum function can be written by passing a function pointer, , as an argument with a value pointing to the appropriate function to use. The cumulative sum expression would then take the form: Here is the implementation:
Finally, we can improve the generic sum function by using a pointer to a function that updates the integer using a specified step size:The function pointed to by takes two arguments, an integer to be updated and the step size. The generic function can now be used to sum applied to integers , which are updated by . The pointer variable, can point to any function that processes an integer and returns an integer. Similarly, can point to any function that returns an updated integer value.
Let us now write a program that reads starting and ending integers as well as step size until . For each set of data read, the program first computes and prints the sum of integers using , and sum of squares using . These two sums are in steps of one, since that is how the functions are written. Next, the program uses the above generic sum function to compute sums of integers and squares in specified step sizes. Figure 14.17 shows the program.
The update function used is , which merely returns plus the step size. The program source files, and , are compiled separately and linked together. A sample run of the program is shown below:
Sample Session:For each set of input data, the output first shows sums of integers and squares in steps of one, and then in specified steps.
Previous:14.2 Dynamic Memory Allocation
Up:14 Storage Class and Scope
Previous Page:14.2.2 Dynamic Arrays
Next Page:14.3.1 Function Pointers as Returned Values