34
Chapter 6 Chapter 6 Pointers Pointers C Programming C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

Embed Size (px)

Citation preview

Page 1: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

Chapter 6Chapter 6PointersPointersC ProgrammingC Programming

© 2003 by The McGraw-Hill Companies, Inc. All rights reserved.

Page 2: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

2

PointersPointersPointers are one of C/C++’s most important and Pointers are one of C/C++’s most important and troublesome features. They provide support for very troublesome features. They provide support for very powerful facilities such as: powerful facilities such as:

dynamic memory allocationdynamic memory allocation and the creation of and the creation of linked listslinked lists..

Allowing a function to modify the contents of an Allowing a function to modify the contents of an argument that has been passed to it ( argument that has been passed to it ( pass-by-pointerpass-by-pointer ). ).

In this chapter however, we will learn the basics of pointers, In this chapter however, we will learn the basics of pointers, how to manipulate them, and avoid potential problems.how to manipulate them, and avoid potential problems.

Page 3: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

3

What are Pointers?What are Pointers?A pointer is a variable that contains a memory address. A pointer is a variable that contains a memory address. Usually this address is the location in memory of another Usually this address is the location in memory of another variable.variable.

For example, if pointer variable For example, if pointer variable xx contains the address of the contains the address of the variable variable yy, then , then xx is said to " is said to "point topoint to"" y y. .

????????Memory

Pointer x

int y;

In the example above the variable declaration (In the example above the variable declaration (yy) allocates ) allocates 4 bytes of memory. Notice that the pointer (4 bytes of memory. Notice that the pointer (xx) points to ) points to the first byte of memory allocated to the integer variable. the first byte of memory allocated to the integer variable.

Page 4: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

4

Pointer DeclarationPointer Declaration

A pointer declaration is declared almost in the same A pointer declaration is declared almost in the same manner as a regular variable. The only difference is that manner as a regular variable. The only difference is that the name of the pointer must be preceded by an the name of the pointer must be preceded by an asterisk asterisk ( ( * * ).).

The general syntax is:The general syntax is:

Examples of declaring pointers:Examples of declaring pointers:

type *var-name;

int *iptr; // define an integer pointerfloat *fptr; // define a float pointerchar *cptr; // define a character pointerdouble *dptr; // define a double pointer

int *ptr = null; // define & initialize a pointer

Note that type used for the pointer indicates the data-type ( base type) of the variable it will point to.

Page 5: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

5

Pointer OperatorsPointer OperatorsThere are two special operators used with pointer:There are two special operators used with pointer:

* a unary operator used the dereference a pointer & a unary operator that returns the memory address of

its operand usually called “the address of “ operator.

For example:For example:

The above places the memory address of the variable The above places the memory address of the variable balancebalance into the pointer variable into the pointer variable balPtrbalPtr. The contents of . The contents of balPtrbalPtr is the memory address of is the memory address of balancebalance and has nothing to and has nothing to do with the actual contentsdo with the actual contentsof of balancebalance..

float balance; // define a float variable float *balPtr; // define a float pointer variable balPtr = &balance; // set the pointer balPtr to the // address of the variable balance

Page 6: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

6

Pointer Operators Pointer Operators (continued)(continued)Assume the variable balance starts at memory Assume the variable balance starts at memory address address 10001000, and contains the value , and contains the value 567.33567.33. The . The following represents what the variables will contain:following represents what the variables will contain:

What will the following code do? What will the following code do?

float balance;float *balPtr;

567.331000

cout << *balPtr << endl;

This code says, display the contents of the float This code says, display the contents of the float variable ( variable ( balancebalance ) )pointed to by the pointer variable pointed to by the pointer variable balPtrbalPtr. The . The ** operator returns theoperator returns thevalue of the variable located at the address specified value of the variable located at the address specified by its operand.by its operand.This is usually referred to as This is usually referred to as dereferencing a dereferencing a pointerpointer. .

Page 7: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

7

Pointer Operators Pointer Operators (continued)(continued)

The float variable The float variable valuevalue will be set to the contents of the will be set to the contents of the float variable pointed to by the float pointer float variable pointed to by the float pointer balPtrbalPtr..

What will the following code do? What will the following code do?

float value;value = *balPtr;

The contents of the float variable pointed to by the float The contents of the float variable pointed to by the float pointer pointer balPtr balPtr will be set to the valuewill be set to the value 891.62 891.62..

What will the following code do? What will the following code do?

*balPtr = 891.62F;

Page 8: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

8

Pointer Operators Pointer Operators (continued)(continued)Here is a sample program using pointers:Here is a sample program using pointers:

#include <iostream>using namespace std;

int main() { float balance; float *balptr; float value;

balance = 3200; balptr = &balance; value = *balptr; // dereference balPtr cout << "balance is: " << value << '\n'; return 0;}

OUTPUT:balance is: 3200

Page 9: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

9

Notes About PointersNotes About Pointers1.1. Note that symbol used for the “Note that symbol used for the “at addressat address” operator ( ” operator ( ** ) is ) is

thethesame symbol used for multiplication. This can be confusing.same symbol used for multiplication. This can be confusing.These operators have These operators have NONO relationship to each other. relationship to each other.

2.2. The The && and and ** have a higher precedence than any of the have a higher precedence than any of the arithmetic operators (therefore the multiplication operator) arithmetic operators (therefore the multiplication operator) except the unary except the unary minusminus, with which they have equal , with which they have equal precedence. precedence.

3.3. The act of using a pointer is often called The act of using a pointer is often called indirection indirection because because youyouare accessing one variable indirectly through another are accessing one variable indirectly through another variable.variable.

4.4. To find the address of a variable use the To find the address of a variable use the & & operator.operator.

5.5. If If xx is a variable, then is a variable, then &x&x is the address of is the address of xx in memory. in memory.

6.6. To gain access to the object that a pointer points to use the To gain access to the object that a pointer points to use the * * indirect operator. This is usually called indirect operator. This is usually called dereferencingdereferencing a a pointer. If pointer. If pp is a pointer, then is a pointer, then *p*p represents the object to represents the object to which which pp currently points. currently points.

Page 10: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

10

The Base Type Is ImportantThe Base Type Is ImportantHow does C/C++ know how many bytes to copy into How does C/C++ know how many bytes to copy into valuevalue from the address pointed to by from the address pointed to by balPtr balPtr in thein the following?following?

The answer is that the The answer is that the base typebase type of the pointer determines of the pointer determines the type of data that the compiler assumes the pointer is the type of data that the compiler assumes the pointer is pointing to. Because pointing to. Because balPtrbalPtr is a float pointer C/C++ copies is a float pointer C/C++ copies 44 bytes of information into bytes of information into valuevalue from the address pointed to from the address pointed to by by balPtrbalPtr..

You should You should ALWAYSALWAYS make sure any pointer variable points make sure any pointer variable points to the correct type of data. The help you C/C++ will not allow to the correct type of data. The help you C/C++ will not allow you to assign one type of pointer to another unless the types you to assign one type of pointer to another unless the types of the pointers are the same. The following code is incorrect:of the pointers are the same. The following code is incorrect:

value = *balPtr;

int *p;double f;// ...p = &f; // ERROR

Page 11: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

11

The Base Type Is Important The Base Type Is Important (continued)(continued)

You can override this restriction, if and when necessary, by You can override this restriction, if and when necessary, by using a using a castcast. The following is technically correct: . The following is technically correct:

This may pose a problem because, even though This may pose a problem because, even though pp is is actually pointing to a floating-point value, the computer actually pointing to a floating-point value, the computer still “still “thinksthinks” that ” that pp is pointing to an integer (because is pointing to an integer (because pp is is an integer pointer). an integer pointer).

int *p ;double f;// ...p = (int *) &f; // Now technically OK

Using a cast to assign one type of pointer to another is not usually a good

idea.

Page 12: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

12

The Base Type Is Important The Base Type Is Important (continued)(continued)

Consider this program.Consider this program.

// This program will not work right.#include <iostream>using namespace std;

int main() { double x, y;

int *p; x = 123.23; p = (int *) &x; // use cast to assign double * to int * y = *p; // What will this do?

cout << y; // What will this print? return 0;}

OUTPUT:????????

Page 13: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

13

Assigning Values Through a Assigning Values Through a PointerPointer

A pointer can be used on the left side of the assignment A pointer can be used on the left side of the assignment operator to assign a value to the location pointed to by operator to assign a value to the location pointed to by the pointer.the pointer.

This says, assign the value This says, assign the value 101101 to location (hopefully to location (hopefully an integer) pointed to by an integer) pointed to by pp..

To increment or decrement the value pointed to by a To increment or decrement the value pointed to by a pointer you can use the following:pointer you can use the following:

The parentheses are required because the The parentheses are required because the ** operator operator has a lower precedence than the has a lower precedence than the ++++ operator. Without operator. Without the parentheses, the address stored in the pointer the parentheses, the address stored in the pointer variable variable pp would be incremented by would be incremented by 11..

(*p)++;

int *p;*p = 101;

Page 14: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

14

Assigning Values Through a Assigning Values Through a PointerPointer

A sample program:A sample program:

#include <iostream>using namespace std;int main() { int *p, num;

p = &num; *p = 100; cout << num << ' '; (*p)++; cout << num << ' '; (*p)--; cout << num << '\n'; return 0;}

OUTPUT:100 101 100

Page 15: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

15

Pointer ExpressionsPointer ExpressionsPointers can be used in most Pointers can be used in most VALIDVALID C/C++ C/C++ expressions, but remember this special rule:expressions, but remember this special rule:

You may need to surround some parts of a You may need to surround some parts of a pointer expression with parentheses to pointer expression with parentheses to obtain the desired results. obtain the desired results.

Page 16: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

16

Pointer ArithmeticPointer ArithmeticThere are only four arithmetic operators that can be used on There are only four arithmetic operators that can be used on pointers:pointers:

++++ ---- ++ --

If If p1p1 is an integer pointer with a value of is an integer pointer with a value of 2,0002,000 then after the then after the expressionexpression

the contents of the contents of p1p1 will be will be 2,0042,004, not , not 2,0012,001. Each time . Each time p1p1 is is incremented, it will point to the incremented, it will point to the nextnext integerinteger in memory. This in memory. This is also true for the decrement operator.is also true for the decrement operator.

For For charchar pointers, an increment/decrement will be as pointers, an increment/decrement will be as ““normalnormal” arithmetic because characters are one byte long. ” arithmetic because characters are one byte long. Every other type of pointer will increase/decrease by the length Every other type of pointer will increase/decrease by the length of its base type.of its base type.

p1++;

Page 17: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

17

Pointer Arithmetic Pointer Arithmetic (continued)(continued)You can also add and subtract integers to or from pointers.

The expression makes p1 point to the ninth element of p1's base type, beyond the one it is currently pointing to.

You cannot add two pointers, but you can subtract one pointer from another pointer provided the are of the same base type. The result will be the number of elements of the base type that separate the two pointers.

p1 = p1 + 9;

Remember:Remember: All pointer arithmetic is All pointer arithmetic is performedperformed relative to the base type of relative to the base type of the pointer.the pointer.

Page 18: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

18

A demonstration program:A demonstration program:#include <iostream>using namespace std;int main() { int *i, j[10]; double *f, g[10]; int x;

i = j; f = g; for(x=0; x<10; x++) cout << i+x << ' ' << f+x << '\n'; return 0;}OUTPUT:0012FEB0 0012FE5C0012FEB4 0012FE640012FEB8 0012FE6C0012FEBC 0012FE740012FEC0 0012FE7C0012FEC4 0012FE840012FEC8 0012FE8C0012FECC 0012FE940012FED0 0012FE9C0012FED4 0012FEA4

Page 19: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

19

Pointers and ArraysPointers and ArraysIn C/C++ pointers and arrays are frequently In C/C++ pointers and arrays are frequently interchangeable. An array name without an index generates interchangeable. An array name without an index generates a pointer to the start of the array. Consider the following:a pointer to the start of the array. Consider the following:

An array name An array name ALWAYSALWAYS points to the first element of the points to the first element of the array. This is array. This is VERYVERY important to understand. Because of important to understand. Because of this, a pointer can be used to access the elements of an this, a pointer can be used to access the elements of an array. Both of the following statements access element array. Both of the following statements access element 55 of of the array.the array.

char str[80];char *p1;

p1 = str; // assigns p1 to point to str[0]

str[4] OR*(p1 + 4) // why the parentheses?

The The ** operator has a higher precedence than the operator has a higher precedence than the ++ operator.operator.

Page 20: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

20

Pointers and ArraysPointers and ArraysC/C++ allows two methods of accessing array elements:C/C++ allows two methods of accessing array elements:

Pointer arithmeticPointer arithmetic Array indexingArray indexing

Pointer arithmetic can be faster than array indexing—Pointer arithmetic can be faster than array indexing—especially if the array is being processed sequentially.especially if the array is being processed sequentially.

The next two sample programs demonstrate both The next two sample programs demonstrate both methods.methods.

Page 21: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

21

Tokenizing program: pointer version.

#include <iostream>#include <cstdio>using namespace std;int main() { char str[80]; char token[80]; char *p, *q; cout << "Enter a sentence: "; gets(str); p = str; // Read a token at a time from the string. while( *p ) { q = token; // set q pointing to start of token // Read characters until a space or the null terminator is encountered. while( *p != ' ' && *p ) { *q = *p; q++; p++; } if( *p ) // advance past the space p++; *q = '\0'; // null terminate the token cout << token << '\n'; } return 0;}

Page 22: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

22

Tokenizing program: array-indexing version.

#include <iostream>#include <cstdio>using namespace std;int main() { char str[80]; char token[80]; int i, j; cout << "Enter a sentence: "; gets(str); // Read a token at a time from the string. for( i = 0; ; i++ ) { // Read characters until a space or the null terminator is encountered. for( j = 0; str[i] != ' ' && str[i]; j++, i++ ) token[j] = str[i]; token[j] = '\0'; // null terminate the token cout << token << '\n'; if( !str[i] ) break; } return 0;}

Page 23: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

23

Indexing a PointerIndexing a PointerIn C/C++, it is possible to index a pointer as if it were In C/C++, it is possible to index a pointer as if it were an array. Here is an example:an array. Here is an example:#include <iostream>#include <cctype>using namespace std;int main() { char str[20] = "hello tom"; char *p; int i; p = str; for(i=0; p[i]; i++) // index a pointer p[i] = toupper(p[i]); cout << p; // display the string return 0;}OUTPUT:HELLO TOM

The The toupper()toupper() function converts a lower case function converts a lower case character to uppercase. character to uppercase.

Page 24: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

24

Are Pointers and Arrays Are Pointers and Arrays Interchangeable?Interchangeable?Pointers and arrays are strongly related, and are interchangeable in Pointers and arrays are strongly related, and are interchangeable in

many cases. But, they are not completely interchangeable. For example:many cases. But, they are not completely interchangeable. For example:

int num[10];int i;for(i = 0; i < 10; i++) { *num = i; // this is OK num++; // ERROR -- cannot modify num}

numnum is an array of integers. It is illegal to modify is an array of integers. It is illegal to modify numnum's value. The reason is that 's value. The reason is that numnum is a constant that is a constant that points to the beginning of an array. Thus you cannot points to the beginning of an array. Thus you cannot increment it. While an array name generates a pointer increment it. While an array name generates a pointer to the beginning of an array, it cannot be changed. It to the beginning of an array, it cannot be changed. It can still be used in pointer-style expressions, as long as can still be used in pointer-style expressions, as long as it is not modified.it is not modified.*(num + 3) = 100; // This is OK because num is not changed

Page 25: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

25

Pointers and String LiteralsPointers and String LiteralsHow does C/C++ handle string literals?How does C/C++ handle string literals?cout << strlen( "C++ Compiler" );

When the compiler encounters a string literal like "When the compiler encounters a string literal like "C+C++ Compiler+ Compiler" above, it stores it in the program's " above, it stores it in the program's string string tabletable and generates a pointer to the string. Therefore and generates a pointer to the string. Therefore the following program is valid:the following program is valid:#include <iostream>using namespace std;int main() { char *s; s = "Pointers are fun to use.\n"; cout << s; return 0;}

The The string tablestring table is a table generated by the compiler and holds the is a table generated by the compiler and holds the strings used by your program. These strings are constants and strings used by your program. These strings are constants and attemptingattempting

to change them will result in a run-time error.to change them will result in a run-time error.

Page 26: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

26

A Comparison ExampleA Comparison ExampleWhen the compiler encounters a string literal like "When the compiler encounters a string literal like "C+C++ Compiler+ Compiler" above, it stores it in the program's " above, it stores it in the program's string string tabletable and generates a pointer to the string. Therefore and generates a pointer to the string. Therefore the following program is valid:the following program is valid:

Page 27: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

27

An example of comparing pointers.An example of comparing pointers.

#include <iostream>using namespace std;int main() { int num[10]; int *start, *end; start = num; end = &num[9]; while( start <= end ) { cout << "Enter a number: "; cin >> *start; start++; } start = num; // reset the starting pointer while( start <= end ) { cout << *start << ' '; start++; } return 0; }

Page 28: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

28

Arrays of PointersArrays of PointersYou can create arrays of pointers just like any other You can create arrays of pointers just like any other data type. data type. int *ipa[10];

This declares an array of This declares an array of 10 integer pointers10 integer pointers. Each . Each element in the array is a pointer to an element in the array is a pointer to an intint value. value.

To assign the address of an To assign the address of an intint variable called variable called varvar to to the the thirdthird element of the array element of the array ipaipa, you would:, you would:

ipa[2] = &var;

x = *ipa[4];

Using the Using the ipaipa array to assign the value of the integer array to assign the value of the integer pointed to by the integer pointer in the pointed to by the integer pointer in the fifthfifth element element of the array to the integer variableof the array to the integer variablexx you would code: you would code:

Page 29: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

29

Initializing Arrays of PointersInitializing Arrays of PointersYou can initialize an array of pointers. A common use You can initialize an array of pointers. A common use for this is to hold pointers to strings.for this is to hold pointers to strings.char *fortunes[] = { "Soon, you will come into some money.\n", "A new love will enter your life.\n", "You will live long and prosper.\n", "Now is a good time to invest for the future.\n", "A close friend will ask for a favor.\n"};

The next slide shows the entire "The next slide shows the entire "fortune cookiefortune cookie" " program. It uses the program. It uses the rand()rand() function to generate a function to generate a random number then uses the modulus operator to random number then uses the modulus operator to obtain a number from obtain a number from 00 to to 44. This value is used to . This value is used to display one of the messages from the array.display one of the messages from the array.

cout << fortunes[1]; // displays the second message

Since string literals are stored in the Since string literals are stored in the string tablestring table, , the array only needs to store pointers to the strings the array only needs to store pointers to the strings not the strings themselves.not the strings themselves.

Page 30: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

30

#include <iostream>#include <cstdlib>#include <conio.h>using namespace std;

char *fortunes[] = { "Soon, you will come into some money.\n", "A new love will enter your life.\n", "You will live long and prosper.\n", "Now is a good time to invest for the future.\n", "A close friend will ask for a favor.\n"};

int main() { int chance; cout << "To see your fortune, press a key: "; // randomize the random number generator while( !kbhit() ) rand(); cout << '\n'; chance = rand(); chance = chance % 5; cout << fortunes[chance]; return 0;}

Page 31: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

31

#include <iostream>#include <cstring>using namespace std;char *keyword[][2] = { // create a table "for", "for(initialization; condition; increment)", "if", "if(condition) ... else ...", "switch", "switch(value) { case-list }", "while", "while(condition) ...", // add the rest of the C++ keywords here "", "" // terminate the list with nulls };

int main() { char str[80]; int i; cout << "Enter keyword: "; cin >> str; for( i = 0; *keyword[i][0]; i++ ) // display syntax if( !strcmp( keyword[i][0], str ) ) cout << keyword[i][1]; return 0;}

Sample execution:Enter keyword: forfor(initialization; condition; increment)

A simple C++ keyword synopsis program:A simple C++ keyword synopsis program:

Page 32: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

32

The Null Pointer ConventionThe Null Pointer ConventionAfter a pointer is declared, but before it has been After a pointer is declared, but before it has been assigned a value, it will contain junk. If you use a assigned a value, it will contain junk. If you use a pointer before giving it a value, pointer before giving it a value, bad thingsbad things happen happen to your program and/or the operating system.to your program and/or the operating system.

By convention, if a pointer contains a By convention, if a pointer contains a nullnull ( (zerozero) ) value, it is assumed to point to nothing. If all unused value, it is assumed to point to nothing. If all unused pointers are set to pointers are set to nullnull and you avoid the use of and you avoid the use of nullnull pointers, you can avoid bad things happening to your pointers, you can avoid bad things happening to your program. This is a good practice to follow.program. This is a good practice to follow.

You can initialize any pointer to null when it is You can initialize any pointer to null when it is declared.declared.

To check for a null pointer , use an if statement To check for a null pointer , use an if statement

float *p = 0; // p is now a null pointer

if( p ) // succeeds if p is not null

if( !p ) // succeeds if p is null

Page 33: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

33

Multiple IndirectionMultiple IndirectionA pointer to a pointer is a form of multiple A pointer to a pointer is a form of multiple indirection, or a chain of pointers (is this heavy or indirection, or a chain of pointers (is this heavy or what?). Usually a pointer contains the address of a what?). Usually a pointer contains the address of a value (value (Single IndirectionSingle Indirection below). below).

Pointer Variable

Pointer Pointer Variable

address value

Single Indirection

address address value

Multiple Indirection

Page 34: Chapter 6 Pointers C Programming © 2003 by The McGraw-Hill Companies, Inc. All rights reserved

34

Problems with PointersProblems with PointersPointers provide great power and are very useful in Pointers provide great power and are very useful in many ways, but when a pointer gets messed up it many ways, but when a pointer gets messed up it can be very hard to find the error.can be very hard to find the error.

Some common causes of problems using pointers:Some common causes of problems using pointers:

uninitialized pointersuninitialized pointers

invalid pointer comparisionsinvalid pointer comparisions

forgetting to reset a pointerforgetting to reset a pointer