Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 6

Pointers

13. POINTERS
Objectives Introduction to pointers Pointer Arithmetic Pointers and Arrays Introduction Pointers are variables that hold addresses in C. They provide much power and utility for the programmer to access and manipulate data in ways not seen in some other languages. They are also useful for passing parameters into functions in a manner that allows a function to modify and return values to the calling routine. When used incorrectly, they also are a frequent source of both program bugs and programmer frustration. 5.1 Introduction to Pointers As a program is executing all variables are stored in memory, each at its own unique address or location. Typically, a variable and its associated memory address contain data values. For instance, when you declare: int count = 5; The value "5" is stored in memory and can be accessed by using the variable "count". A pointer is a special type of variable that contains a memory address rather than a data value. Just as data is modified when a normal variable is used, the value of the address stored in a pointer is modified as a pointer variable is manipulated. Usually, the address stored in the pointer is the address of some other variable. int *ptr; ptr = &count /* Stores the address of count in ptr */ /* The unary operator & returns the address of a variable */ To get the value that is stored at the memory location in the pointer it is necessary to dereference the pointer. Dereferencing is done with the operator "*". int total; total = *ptr; /* The value in the address stored in ptr is assigned to total */ The best way to learn how to use pointers is by example. There are examples of the types of operations already discussed below. Pointers are a difficult topic. Don't worry if everything isn't clear yet. Declaration and Initialization Declaring and initializing pointers is fairly easy. int main() { int j; int k;

Pointers int l; int *pt1; /* Declares an integer pointer */ int *pt2; /* Declares an integer pointer */ float values[100]; float results[100]; float *pt3; /* Declares a float pointer */ float *pt4; /* Declares a float pointer */ j = 1; k = 2; pt1 = &j; /* pt1 contains the address of the variable j */ pt2 = &k; /* pt2 contains the address of variable k */ pt3 = values; /* pt3 contains the address of the first element of values */ pt3 = &values[0]; /* This is the equivalent of the above statement */ return 0; } Pointer De-referencing/Value Assignment Dereferencing allows manipulation of the data contained at the memory address stored in the pointer. The pointer stores a memory address. Dereferencing allows the data at that memory address to be modified. The unary operator "*" is used to dereference. For instance: *pt1 =*pt1 + 2; This adds two to the value "pointer to" by pt1. That is, this statement adds 2 to the contents of the memory address contained in the pointer pt1. So, from the main program, pt1 contains the address of j. The variable "j" was initialized to 1. The effect of the above statement is to add 2 to j. The contents of the address contained in a pointer may be assigned to another pointer or to a variable. *pt2 = *pt1; /* assigns the contents of the memory pointed to by pt1 */ /* to the contents of the memory pointer to by pt2; */ k = *pt2; /* assigns the contents of the address pointer to by pt2 to k. */ 5.2 Pointer Arithmetic Part of the power of pointers comes from the ability to perform arithmetic on the pointers themselves. Pointers can be incremented, decremented and manipulated using arithmetic expressions. Recall the float pointer "pt3" and the float array "values" declared above in the main program. pt3 = &values[0]; /* The address of the first element of "values" is stored in pt3*/ pt3++; /* pt3 now contains the address of the second element of values */

Pointers *pt3 = 3.1415927; /* The second element of values now has pie (actually pi)*/ pt3 += 25; /* pt3 now points to the 27th element of values */ *pt3 = 2.22222; / The 27th element of values is now 2.22222 */ pt3 = values; /*pt3 points to the start of values, now */ for (ii = 0; ii < 100; ii++) { *pt3++ = 37.0; /* This sets the entire array to 37.0 */ } pt3 = &values[0]; /* pt3 contains the address of the first element of values */ pt4 = &results[0]; /* pt4 contains the address of the first element of results */ for (ii=0; ii < 100; ii++) { *pt4 = *pt3; /* The contents of the address contained in pt3 are assigned to the contents of the address contained in pt4 */ pt4++; pt3++; } 5.3 Pointers and Arrays In some cases, a pointer can be used as a convenient way to access or manipulate the data in an array. Suppose the following declarations are made, Float temperatures[31]; /* An array of 31 float values, the daily temperatures in a month */ float *temp; /* A pointer to type float */ Since temp is a float pointer, it can hold the address of a float variable. The address of the first element of the array temperatures can be assigned to temp in two ways. temp = &temperatures[0]; temp = temperatures; /* This is an alternate notation for the first element of the array. Same as temperatures = &temperatures[0]. */ The temperature of the first day can be assigned in two ways. temperatures[0] = 29.3; /* brrrrrrr */ *temp = 15.2; /* BRRRRRRR */ Other elements can be updated via the pointer, as well. temp = &temperatures[0];

Pointers *(temp + 1) = 19.0; /* Assigns 19.0 to the second element of temperatures */ temp = temp + 9; /* temp now has the address of the 10th element of the array */ *temp = 25.0; /* temperatures[9] = 25, remember that arrays are zero based, so the tenth element is at index 9. */ temp++; /* temp now points at the 11th element */ *temp = 40.9; /* temperatures[10] = 40.9 */ Pointers are particularly useful for manipulating strings, which are stored as null terminated character arrays in C. A character pointer can also be assigned the address of a string constant or of a character array. char *lpointer = "Hello World"; /* Assigns the address of the literal to lpointer */ char *apointer = str1; /* Assigns the starting address of str1 to apointer */ char *apointer = &str1[0]; /* Assigns the starting address of str1 to apointer */ There is no direct means in the C language to copy one array to another, or one string to another. It must be done either with a standard library function or element wise in a loop. As an example, here is a program that counts the occurrences of each lowercase letter of the alphabet in a string. #include <stdio.h> int main() { int i,j; char buffer[120]; /* Holds input strings */ char *pt; /* A pointer to data type char */ char alphabet[27] = "abcdefghijklmnopqrstuvwxyz"; int alphaCount[26]; /* an array of counts */ /* Initialize counts */ for (i = 0; i < 26; i++) { alphaCount[i] = 0; } while ((pt = gets(buffer)) != NULL) { for (i = 0; i < 120 && buffer[i] != '\0'; i++) { for (j = 0; j < 26; j++) { if (buffer[i] == alphabet[j]) {

Pointers alphaCount[j]++; } } } } for (i = 0; i < 26; i++) { printf("Found %d occurrences of %c\n", alphaCount[i],alphabet[i]); } return 0; } gets reads a line of input into a character array. Its prototype is: char *gets(char *buffer); It returns a pointer to the character string if successful, or NULL if end of file is reached or if an error has occurred. The string is also read into the character array specified as an argument. The character string will be terminated be a "\0", which is standard for C. The first step in this program is to initialize the count array. When you use an automatic variable, you must initialize it. Otherwise, it contains whatever data happened to be at the memory location it is stored in. This will be discussed further in the lesson on variable scope. The while loop in this program reads lines of input until an end of file is encountered. If you run this program, remember that an end of file, EOF, is entered as a control-d or a control-z from you keyboard. This is, after you type the last line of text, type control-z or control-d to enter the End of File character. For each line read in, each character in the line is compared against each letter in the alphabet. If a match is found the appropriate count is incremented. The last step in this program writes out the results. Summary Only an address of a variable can be stored in a pointer variable. Remember that the definition for a pointer variable allocates memory only for the pointer variable, not for the variable to which it is pointing. We cannot store the address of a variable of one type into a pointer variable of another type. The value of a variable cannot be assigned to a pointer variable. When we pass a parameter by address, the corresponding formal parameter must be a pointer variable. When an array is passed as an argument to a function, a pointer is actually passed. In the header function, we must declare such arrays with proper size, except the first, which is optional.

Pointers

Review Questions State whether true or false. 1. Pointer variables declared using the address operator. 2. A pointer can never be subtracted from another pointer. 3. An integer can be added to a pointer. 4. A pointer can hold the address of another pointer. Fill in the blanks. 1. A pointer variable contains as its value of the ________ of another variable. 2. The ________ operator returns the value of the variable to which its operand points. 3. A pointer to an array always holding the address of _________ element. Programming Exercises 1. Write a program using pointers to read in an array of integer and print its elements in reverse order. 2. Write a function (using a pointer parameter) that reverses the elements of a given array.

You might also like