Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.

Similar presentations


Presentation on theme: "Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy."— Presentation transcript:

1 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 10: Pointers

2 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10.1 Pointers and the Address Operator Each variable in a program is stored at a unique address in memory Use the address operator & to get the address of a variable: int num = -23; cout << &num; // prints address // in hexadecimal The address of a memory location is a pointer 10-2

3 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10.2 Pointer Variables Pointer variable (pointer): variable that holds an address Pointers provide an alternate way to access memory locations Because a pointer variable holds the address of another piece of data, it "points" to the data 10-3

4 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 4 Something Like Pointers: Arrays We have already worked with something similar to pointers, when we learned to pass arrays as arguments to functions. For example, suppose we use this statement to pass the array numbers to the showValues function: showValues(numbers, SIZE);

5 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 5 Something Like Pointers : Arrays The values parameter, in the showValues function, points to the numbers array. C++ automatically stores the address of numbers in the values parameter.

6 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 6 Something Like Pointers: Reference Variables We have also worked with something like pointers when we learned to use reference variables. Suppose we have this function: void getOrder(int &donuts) { cout > donuts; } And we call it with this code: int jellyDonuts; getOrder(jellyDonuts);

7 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 7 Something Like Pointers: Reference Variables The donuts parameter, in the getOrder function, points to the jellyDonuts variable. C++ automatically stores the address of jellyDonuts in the donuts parameter.

8 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 8 Pointer Variables Pointer variables are yet another way using a memory address to work with a piece of data. Pointers are more "low-level" than arrays and reference variables. This means you are responsible for finding the address you want to store in the pointer and correctly using it.

9 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointer Variables Definition: int *intptr; Read as: “ intptr can hold the address of an int” or “the variable that intptr points to has type int” Spacing in definition does not matter: int * intptr; 10-9

10 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointer Variables Assignment: int num = 25; int *intptr; intptr = &num; Memory layout: Can access num using intptr and indirection operator * : cout << intptr; // prints 0x4a00 cout << *intptr; // prints 25 10-10 numintptr 25 0x4a00 address of num : 0x4a00

11 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 11

12 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 12 The Indirection Operator The indirection operator ( * ) dereferences a pointer. It allows you to access the item that the pointer points to. int x = 25; int *intptr = &x; cout << *intptr << endl; This prints 25.

13 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 13

14 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 14 Reusing a pointer When we apply the indirection operator to the pointer ptr, we are not working with ptr as and address but with the item to which ptr points Thus, we can reuse ptr to point to different variables and make changes to the value of each variable

15 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 15 Reusing a pointer int main() { int x = 25, y = 50, z = 75; // Three int variables int *ptr; // Pointer variable // Display the contents of x, y, and z. cout << "Here are the values of x, y, and z:\n"; cout << x << " " << y << " " << z << endl; // Use the pointer to manipulate x, y, and z. ptr = &x; // Store the address of x in ptr. *ptr += 100; // Add 100 to the value in x. ptr = &y; // Store the address of y in ptr. *ptr += 100; // Add 100 to the value in y. ptr = &z; // Store the address of z in ptr. *ptr += 100; // Add 100 to the value in z. // Display the contents of x, y, and z. cout << "Once again, here are the values of x, y, and z:\n"; cout << x << " " << y << " " << z << endl; return 0; } OUTPUT: Here are the values of x, y, and z: 25 50 75 Once again, here are the values of x, y, and z: 125 150 175

16 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10.3 The Relationship Between Arrays and Pointers Array name is starting address of array int vals[] = {4, 7, 11}; cout << vals; // displays 0x4a00 cout << vals[0]; // displays 4 10-16 4711 starting address of vals : 0x4a00

17 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Relationship Between Arrays & Pointers Array name can be used as a pointer constant int vals[] = {4, 7, 11}; cout << *vals; // displays 4 Pointer can be used as an array name int *valptr = vals; cout << valptr[1]; // displays 7 10-17

18 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 18

19 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers in Expressions Given: int vals[]={4,7,11}; int *valptr = vals; What is valptr + 1 ? It means (address in valptr ) + (1 * size of an int ) cout << *(valptr+1); // displays 7 cout << *(valptr+2); // displays 11 Must use ( ) in expression 10-19

20 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Array Access Array elements can be accessed in many ways 10-20 Array access methodExample array name and [ ] vals[2] = 17; pointer to array and [ ] valptr[2] = 17; array name and subscript arithmetic *(vals+2) = 17; pointer to array and subscript arithmetic *(valptr+2) = 17; (vals + 2)= address of 3rd element

21 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Array Access Array notation vals[i] is equivalent to the pointer notation *(vals + i) No bounds checking performed on array access 10-21

22 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 22

23 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 23 Array Names vs Pointer Variables The only difference between array names and pointer variables is that you can not change the address an array name points to –Array names are pointer constants double readings [20], totals[20] double *dprt; LEGAL: dptr = readings; dptr = totals; ILLEGAL: readings = totals; totals = dptr;

24 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10.4 Pointer Arithmetic Some arithmetic operators can be used with pointers: –Increment and decrement operators ++, -- –Integers can be added to or subtracted from pointers using the operators +, -, +=, and -= –One pointer can be subtracted from another by using the subtraction operator - 10-24

25 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointer Arithmetic Assume the variable definitions int vals[]={4,7,11}; int *valptr = vals; Examples of use of ++ and -- valptr++; // points at 7 valptr--; // now points at 4 10-25

26 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-26 More on Pointer Arithmetic Assume the variable definitions: int vals[]={4,7,11}; int *valptr = vals; Example of the use of + to add an int to a pointer: cout << *(valptr + 2) This statement will print 11

27 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-27 Assume the variable definitions: int vals[]={4,7,11}; int *valptr = vals; Example of use of +=: valptr = vals; // points at 4 valptr += 2; // points at 11 More on Pointer Arithmetic

28 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10-28 More on Pointer Arithmetic Assume the variable definitions int vals[] = {4,7,11}; int *valptr = vals; Example of pointer subtraction valptr += 2; cout << valptr - vals; This statement prints 2 : the number of int s between valptr and vals

29 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 29 Pointer Arithmetic int vals[]={4,7,11}; int *valptr = vals; cout<<"\nvalptr++: "<<valptr++; cout<<" *valptr: "<<*valptr<<endl; cout<<"valptr--: "<<valptr--; cout<<" *valptr: "<<*valptr<<endl; cout <<"*(valptr+2): "<< *(valptr + 2)<<endl; valptr = vals; valptr+=2; cout<<"valptr+=2: "<<valptr<<endl; int y = valptr-vals; cout<<"valptr: "<<valptr<<" vals: "<<vals; cout<<" *valptr: "<<*valptr<<" *vals: "<<*vals<<endl; cout<<" valptr minus vals: "<<y<<endl; valptr++: 0x22ff20 *valptr: 7 valptr--: 0x22ff24 *valptr: 4 *(valptr+2): 11 valptr+=2: 0x22ff28 valptr: 0x22ff28 vals: 0x22ff20 *valptr: 11 *vals: 4 valptr minus vals: 2

30 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 30 From Program 9-9

31 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 31 Pointer Arithmetic - Summary OperationExample int vals[]={4,7,11}; int *valptr = vals; ++, -- valptr++; // points at 7 valptr--; // now points at 4 +, - (pointer and int ) cout << *(valptr + 2); // 11 +=,-= (pointer and int ) valptr = vals; // points at 4 valptr += 2; // points at 11 - (pointer from pointer) cout << valptr–val; // difference //(number of ints) between valptr // and val

32 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10.5 Initializing Pointers Can initialize to NULL or 0 (zero) int *ptr = NULL; Can initialize to addresses of other variables int num, *numPtr = &num; int val[ISIZE], *valptr = val; Initial value must have correct type float cost; int *ptr = &cost; // won't work Can test for an invalid address for ptr with: if (!ptr)... 10-32

33 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10.6 Comparing Pointers Relational operators can be used to compare addresses in pointers Comparing addresses in pointers is not the same as comparing contents pointed at by pointers: if (ptr1 == ptr2) // compares // addresses if (*ptr1 == *ptr2) // compares // contents 10-33

34 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 34 Comparing Pointers Addresses grow larger for each subsequent element in an array array[0]array[1]array[2]array[3]array[4] 0x5A00 (Addresses) 0x5A040x5A080x5A0C0x5A10

35 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10.7 Pointers as Function Parameters A pointer can be used as a function parameter It gives the function access to the original argument, much like a reference parameter does, so that the argument can be changed within the function –In C, the only way to pass a variable by reference is to use a pointer –The C++ library has many functions that use pointers as parameters 10-35

36 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers as Function Parameters Requires: 1) asterisk * on parameter in prototype and heading void getNum(int *ptr); // ptr is pointer to an int 2) asterisk * in body to dereference the pointer cin >> *ptr; 3) address as argument to the function getNum(&num); // pass address of num to getNum 10-36

37 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 37 Example #include using namespace std; void swap(int*, int*); int main() { int x=5, y=10; cout<<"Before swap: x "<<x<<" y "<<y<<endl; swap(&x,&y); cout<<"After swap: x "<<x<<" y "<<y<<endl; return 0; } void swap(int* x, int* y) { int temp; temp = *x; *x = *y; *y = temp; } OUTPUT: Before swap: x 5 y 10 After swap: x 10 y 5

38 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 38 (Program Continues) When the getnumber function is called in line 15, the address of the number variable is passed as the argument. After the function executes, the value entered by the user is stored in number.

39 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 39 cin>>input would store the value entered by the user in input as if the value were an address. Thus, input would no longer point to the number variable in function main

40 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 40 Pointers Variables to Arrays To pass an array sales to a function using a pointer, include the following FUNCTION PROTOTYPE void getSales(double *, int); double totalSales(double *, int); FUNCTION CALL IN MAIN getSales(sales,4); double totsale=totalSales(sales,4);

41 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 41 Pointers Variables to Arrays FUNCTIONS void getSales(double* array, int size) { for (int count=0; count<size; count++) { cout<<“Enter the sales figure for each quarter”; cout<<(count+1)<<“: “; cin>>array[count]; } double totalSales(double* array, int size) { double sum=0.0; for (int count=0; count<size; count++) { sum += *array; array++; } return sum; }

42 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10.8 Pointers to Constants and Constant Pointers Pointer to a constant: cannot change the value that is pointed at Constant pointer: address in pointer cannot change once pointer is initialized To pass the address of a const item into a pointer, the pointer must be defined as a pointer to a const item –What is the purpose of a const item? 10-42

43 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers to Constant Must use const keyword in pointer definition: const double taxRates[] = {0.65, 0.8, 0.75}; const double *ratePtr; Use const keyword for pointers in function headers to protect data from modification from within function 10-43

44 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 44 Pointers to Constants Example: Suppose we have the following definitions: const int SIZE = 6; const double payRates[SIZE] = { 18.55, 17.45, 12.85, 14.97, 10.35, 18.89 }; double overtimeRates[SIZE] = { 18.55, 17.45, 12.85, 14.97, 10.35, 18.89 }; In this code, payRates is an array of constant doubles and overtimeRates is an array of non-constant doubles

45 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 45 Pointers to Constants Suppose we wish to pass the payRates array to a function? Here's an example of how we can do it. FUNCTION PROTOTYPE: void displayPayRates(const double *, int); CALL FROM MAIN: displayPayRates(payRates,SIZE); FUNCTION: void displayPayRates(const double *rates, int size) { for (int count = 0; count < size; count++) { cout << "Pay rate for employee " << (count + 1) << " is $" << *(rates + count) << endl; } } The parameter, rates, is a pointer to const double.

46 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 46 Pointers to Constants A function that uses a parameter that points to a const can also accept the address of a non- constant argument CALL FROM MAIN: displayPayRates(overtimeRates,SIZE);

47 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointer to Constant – What does the Definition Mean? 10-47

48 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 48 Pointer That Is a Constant Pointer

49 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 49 Constant Pointers to Constants

50 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 50 Pointer Types const double * rates A pointer to a const points to a constant item –The data that the pointer points to can not change, but the pointer itself can change int * const ptr With a const pointer, the pointer itself is constant. –Once the pointer is initialized with an address, it can not point to anything else but the contents of what it points to can change const int * const ptr With a const pointer to a const, can not use ptr to change the contents of value

51 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Constant Pointers Defined with const keyword adjacent to variable name: int classSize = 24; int * const classPtr = &classSize; Must be initialized when defined Can be used without initialization as a function parameter –Initialized by argument when function is called –Function can receive different arguments on different calls While the address in the pointer cannot change, the data at that address may be changed 10-51

52 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 52 Constant Pointers A constant pointer, ptr, is a pointer that is initialized with an address, and cannot point to anything else. We can use ptr to change the contents of value Example int value = 22; int * const ptr = &value;

53 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 53 Regular Pointers Regular Pointer value2: 987 ptr2: 0x22ff0c *ptr2: 987 value2: 12345 ptr2: 0x22ff0c *ptr2: 12345 value3: 5678 ptr2: 0x22ff08 *ptr2: 5678 int value2= 987; int value3=5678; int * ptr2 = &value2; cout<<"\nRegular Pointer\n"; cout <<"value2: "<<value2<<" ptr2: "<<ptr2<<" *ptr2: "<<*ptr2<<endl; *ptr2=12345; cout <<"value2: "<<value2<<" ptr2: "<<ptr2<<" *ptr2: "<<*ptr2<<endl; //LEGAL WITH REGUALR POINTER, CHANGE OF ADDRESS ptr2= &value3; cout <<"value3: "<<value3<<" ptr2: "<<ptr2<<" *ptr2: "<<*ptr2<<endl;

54 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 54 Constant Pointers Constant Pointer value: 22 ptr: 0x22ff18 *ptr: 22 value: 99 ptr: 0x22ff18 *ptr: 99 value: 12345 ptr: 0x22ff18 *ptr: 12345 int value = 22; int value4 = 99; int * const ptr = &value; cout<<"\nConstant Pointer\n"; cout <<"value: "<<value<<" ptr: "<<ptr<<" *ptr: "<<*ptr<<endl; value=99; cout <<"value: "<<value<<" ptr: "<<ptr<<" *ptr: "<<*ptr<<endl; *ptr=12345; cout <<"value: "<<value<<" ptr: "<<ptr<<" *ptr: "<<*ptr<<endl; // THIS CAN NOT BE DONE, CAN NOT CHANGE ADDRESS THAT ptr POINTS TO // ptr = &value4;

55 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 55 Constant Pointers In the legal example, the code changes the data that ptr points to since ptr does not point to a constant In the illegal example, the code is trying to change the address that ptr points to LEGAL: void setToZero(int * const ptr) { *ptr = 0; } ILLEGAL: void setToZero(int * const ptr) { ptr = 0; }

56 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 56 Pointer to a Constant value6: 666 ptr6: 0x22ff74 *ptr6: 666 value6: 6666 ptr6: 0x22ff74 *ptr6: 6666 value7: 777 ptr6: 0x22ff70 *ptr6: 777 int value6 = 666; int value7 = 777; const int * ptr6 = &value6; cout<<"\nPointer to a Constant\n"; cout <<"value6: "<<value6<<" ptr6: "<<ptr6<<" *ptr6: "<<*ptr6<<endl; value6=6666; cout <<"value6: "<<value6<<" ptr6: "<<ptr6<<" *ptr6: "<<*ptr6<<endl; ptr6=&value7; cout <<"value7: "<<value7<<" ptr6: "<<ptr6<<" *ptr6: "<<*ptr6<<endl; //CAN NOT BE DONE // *ptr6=6543;

57 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 57 Constant Pointer to a Constant value5: 55 ptr5: 0x22ff74 *ptr5: 55 value5: 777 ptr5: 0x22ff74 *ptr5: 777 int value5 = 55; int value12 = 1212; const int * const ptr5 = &value5; cout<<"\nConstant Pointer to a Constant\n"; cout <<"value5: "<<value5<<" ptr5: "<<ptr5<<" *ptr5: "<<*ptr5<<endl; value5=777; cout <<"value5: "<<value5<<" ptr5: "<<ptr5<<" *ptr5: "<<*ptr5<<endl; //CAN NOT PERFORM EITHER ONE OF THESE OPERATIONS // ptr5 = &value12; // *ptr5=6543;

58 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 58 Constant Pointers to Constants A constant pointer to a constant is: –a pointer that points to a constant –a pointer that cannot point to anything except what it is pointing to Example: int value = 22; const int * const ptr = &value;

59 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10.9 Dynamic Memory Allocation Can allocate storage for a variable while program is running Computer returns address of newly allocated variable Uses new operator to allocate memory: double *dptr; dptr = new double; *dptr = 56.78; //assign value total +=*dptr; // use in computation new returns address of memory location 10-59

60 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Memory Allocation Can also use new to allocate array: const int SIZE = 25; arrayPtr = new double[SIZE]; Can then use [] or pointer arithmetic to access array: for(i = 0; i < SIZE; i++) *arrayPtr[i] = i * i; or for(i = 0; i < SIZE; i++) *(arrayPtr + i) = i * i; Program will throw an exception and terminate if not enough memory available to allocate 10-60

61 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Releasing Dynamic Memory Use delete to free dynamic memory delete dptr; Use delete [] to free dynamic array memory delete [] arrayptr; Only use delete with dynamic memory! 10-61

62 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 62

63 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 63 Notice that in line 49 the value 0 is assigned to the sales pointer. It is a good practice to store 0 in a pointer variable after using delete on it. First, it prevents code from inadvertently using the pointer to access the area of memory that was freed. Second, it prevents errors from occurring if delete is accidentally called on the pointer again. The delete operator is designed to have no effect when used on a null pointer.

64 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dangling Pointers and Memory Leaks A pointer is dangling if it contains the address of memory that has been freed by a call to delete. –Solution: set such pointers to 0 as soon as memory is freed. A memory leak occurs if no-longer-needed dynamic memory is not freed. The memory is unavailable for reuse within the program. –Solution: free up dynamic memory after use 10-64

65 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10.10 Returning Pointers from Functions Pointer can be the return type of function int* newNum(); Function must not return a pointer to a local variable in the function Function should only return a pointer –to data that was passed to the function as an argument –to dynamically allocated memory –You must be sure the item the pointer references still exists 10-65

66 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 66 Returning Pointers from Functions #include using namespace std; char *findNull(char*); int main(){ char *s = {"Ira Rudowsky"}; cout<<“String at null is ["<<(findNull(s))<<"]"<<endl; return 0; } // locate the null terminator in a string and returns a pointer to it // The char * return type in the function header indicates that the function // returns a pointer to a character char *findNull(char *str) { int count=0; cout<<"count: "<<count<<" "; char *ptr = str; while (*ptr !='\0') { cout<<" *ptr: "<<*ptr<<" ptr: "<<ptr<<" &ptr: "<<&ptr<<endl; count++; ptr++; cout<<"count: "<<count<<" "; } cout<<endl; return ptr; }

67 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 67 Returning Pointers from Functions OUTPUT: count: 0 *ptr: I ptr: Ira Rudowsky&ptr: 0x22ff40 count: 1 *ptr: r ptr: ra Rudowsky &ptr: 0x22ff40 count: 2 *ptr: a ptr: a Rudowsky &ptr: 0x22ff40 count: 3 *ptr: ptr: Rudowsky &ptr: 0x22ff40 count: 4 *ptr: R ptr: Rudowsky &ptr: 0x22ff40 count: 5 *ptr: u ptr: udowsky &ptr: 0x22ff40 count: 6 *ptr: d ptr: dowsky &ptr: 0x22ff40 count: 7 *ptr: o ptr: owsky &ptr: 0x22ff40 count: 8 *ptr: w ptr: wsky &ptr: 0x22ff40 count: 9 *ptr: s ptr: sky &ptr: 0x22ff40 count: 10 *ptr: kptr: ky &ptr: 0x22ff40 count: 11 *ptr: y ptr: y &ptr: 0x22ff40 count: 12 String at null is []

68 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 68 Returning Pointers from Functions #include #include // For rand and srand #include // For the time func using namespace std; // Function prototype int *getRandomNumbers(int); int main() { int *numbers; // To point to the numbers // Get an array of five random numbers. numbers = getRandomNumbers(5); // Display the numbers. for (int count = 0; count < 5; count++) cout << numbers[count] << endl; // Free the memory. delete [] numbers; numbers = 0; return 0; } /* The getRandomNumbers function returns a pointer to an array of random integers. The parameter indicates the number of numbers requested. */ int *getRandomNumbers(int num) { int *array; // Array to hold the numbers // Return null if num is zero or negative. if (num <= 0) return NULL; // Dynamically allocate the array. array = new int[num]; // Seed the random number generator by passing //the return value of time(0) to srand. srand( time(0) ); // Populate the array with random numbers. for (int count = 0; count < num; count++) array[count] = rand(); // Return a pointer to the array. return array; }

69 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 69 Exercise Complete the following program skeleton. The program asks for a value in inches and calls a function convert that computes the value in centimeters and passes it back to main #include using namespace std; FUNCTION PROTOTYPE FOR convert double convert(double *); int main() { double measurement; cout<<"Enter a length in inches to be converted to centimeters: "; cin>>measurement; convert(&measurement); cout<<fixed<<setprecision(4); cout<<“\nValue in centimeters: "<<measurement<<endl; return 0; } FUNCTION convert

70 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10.11 Pointers to Class Objects and Structures Can create pointers to objects and structure variables struct Student {…}; class Square {…}; Student stu1; Student *stuPtr = &stu1; Square sq1[4]; Square *squarePtr = &sq1[0]; Need () when using * and. (*stuPtr).studentID = 12204; as the dot selector has higher priority than the * operator 10-70

71 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Structure Pointer Operator Simpler notation than (*ptr).member Use the form ptr->member: stuPtr->studentID = 12204; squarePtr->setSide(14); in place of the form (*ptr).member: (*stuPtr).studentID = 12204; (*squarePtr).setSide(14); 10-71

72 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Memory with Objects Can allocate dynamic structure variables and objects using pointers: stuPtr = new Student; Can pass values to constructor: squarePtr = new Square(17); delete causes destructor to be invoked: delete squarePtr; Project DynamicAllocationObjects 10-72

73 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Pointers to Class Objects as Function Parameters Pointers to structures and class variables can be passed to function parameters The function receiving the pointer can then use it to modify members of the structure Project DynamicAllocationObjectsAsFuncParms 10-73

74 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Stopping Memory Leaks When using DAM, make sure that each call to new is eventually followed by a call to delete that frees the allocated memory and returns it to the heap. If not, memory leaks will occur in which the program loses track of dynamically allocated storage and never calls delete to free the memory –The function that invokes new should also be the function that invokes delete –A class that needs to dynamically allocate storage should invoke new in its constructor and invoke the corresponding delete in its destructor Project MemoryLeaks 10-74

75 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10.12 Selecting Members of Objects Situation: A structure/object contains a pointer as a member. There is also a pointer to the structure/ object. Problem: How do we access the pointer member via the structure/object pointer? struct GradeList { string courseNum; int * grades; } GradeList test1, *testPtr = &test1; 10-75

76 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Selecting Members of Objects 10-76 ExpressionMeaning testPtr->grades Access the grades pointer in test1. This is the same as (*testPtr).grades *testPtr->grades Access the value pointed at by testPtr->grades. This is the same as *(*testPtr).grades *test1.grades Access the value pointed at by test1.grades

77 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Selecting Members of Objects struct GradeInfo { char name[25]; int *testScores; double average; } GradeInfo student1; Displays value pointed to by the testScores member cout<<*student1.testScores; GradeInfo *stPtr; //pointer to structure cout testScores; stPtr->testScores (*stPtr).testScores *stPtr->testScores *(*stPtr).testScores 10-77

78 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley #include //Project - PointerToStructures using namespace std; class GradeInfo { public: char name[25]; int *testScores; double average; GradeInfo (){ testScores = new int;} }; int main(){ GradeInfo student1; GradeInfo *grPtr = &student1; *student1.testScores = 98; cout<<"<<*student1.testScores "<<*student1.testScores<<endl; cout<<"&student1 "<<&student1<<endl; cout<<"grPtr "<<grPtr<<endl; cout<<"&grPtr "<<&grPtr<<endl; cout<<"student1.testScores "<<student1.testScores<<endl; cout<<"(*(&student1).testScores "<<(*(&student1)).testScores<<endl; *(*grPtr).testScores=90; cout<<"grPtr "<<*(*grPtr).testScores<<endl<<endl; cout testScores " testScores<< " *(grPtr).testScores "<<(*grPtr).testScores<<endl; cout testScores " testScores<< " *(*grPtr).testScores "<<*(*grPtr).testScores<<endl; return 0; } 10-78

79 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley *student1.testScores 98 &student1 0x22ff40 grPtr 0x22ff40 &grPtr 0x22ff3c student1.testScores 0x3e2498 (*(&student1).testScores 0x3e2498 grPtr 90 grPtr->testScores 0x3e2498 *(grPtr).testScores 0x3e2498 *grPtr->testScores 90 *(*grPtr).testScores 90 10-79

80 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 80 Arrays of Pointers This example will have an array donations of unsorted integers An array of pointers is defined so that each element of donations is pointed to by an element of the array arrPtr We will then sort arrPtr based on the value stored and then display the sorted values without actually sorting the array donations

81 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 81 Arrays of Pointers #include using namespace std; void arrSelectSort(int *[], int); void showArray(int [], int); void showArrPtr(int *[], int); int main() { const int NUM_DONATIONS = 15; // Number of donations // An array containing the donation amounts. int donations[NUM_DONATIONS] = {5,100, 5,25, 10, 5, 25, 5, 5, 100, 10, 15, 10, 5, 10 }; int *arrPtr[NUM_DONATIONS]; // An array of pointers to int. // Each element of arrPtr is a pointer to an int element in donations for (int count = 0; count < NUM_DONATIONS; count++) arrPtr[count] = &donations[count]; arrSelectSort(arrPtr, NUM_DONATIONS); // Sort the elements of the array of pointers. // Display the donations using the array of pointers in sorted order. cout << "The donations, sorted in ascending order are: \n"; showArrPtr(arrPtr, NUM_DONATIONS); // Display the donations in their original order. cout << "The donations, in their original order are: \n"; showArray(donations, NUM_DONATIONS); return 0; }

82 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 82 //**************************************************************** // Definition of function arrSelectSort. * // This function performs an ascending order selection sort on * // array, which is an array of pointers. Each element of array * // points to an element of a second array. After the sort, * // array will point to the elements of the second array in * // ascending order. * //**************************************************************** void arrSelectSort(int *array[], int size) { int startScan, minIndex; int *minElem; for (startScan = 0; startScan < (size - 1); startScan++) { minIndex = startScan; minElem = array[startScan]; cout<<"OUTER LOOP: minElem: "<<minElem<<" *minElem: "<<*minElem<<endl; for(int index = startScan + 1; index < size; index++) { cout<<" (array["<<index<<"]): "<<(array[index])<<" *minElem: "<<*minElem<<endl; if (*(array[index]) < *minElem) { minElem = array[index]; minIndex = index; cout<<"NEW minElem= "<<*minElem<<endl; } array[minIndex] = array[startScan]; array[startScan] = minElem; cout<<"After loop on startScan="<<startScan<<endl; for (int k=0;k<size;k++) cout<<array[k]<<" "; cout<<endl; for (int k=0;k<size;k++) cout<<*array[k]<<" ";cout<<endl; }

83 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 83 Arrays of Pointers //************************************************************* // Definition of function showArray. * // This function displays the contents of array. size is the * // number of elements. * //************************************************************* void showArray(int array[], int size) { for (int count = 0; count < size; count++) cout << array[count] << " "; cout << endl; } //************************************************************** // Definition of function showArrPtr. * // This function displays the contents of the array pointed to * // by array. size is the number of elements. * //************************************************************** void showArrPtr(int *array[], int size) { for (int count = 0; count < size; count++) cout << *(array[count]) << " "; cout << endl; }

84 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 84 Arrays of Pointers arrPtr[0]: 0x22ff50 *arrPtr[0]: 10 &donations[0]: 10 arrPtr[1]: 0x22ff54 *arrPtr[1]: 3 &donations[1]: 3 arrPtr[2]: 0x22ff58 *arrPtr[2]: 2 &donations[2]: 2 arrPtr[3]: 0x22ff5c *arrPtr[3]: 7 &donations[3]: 7 OUTER LOOP: minElem: 0x22ff50 *minElem: 10 (array[1]): 0x22ff54 *minElem: 10 NEW *minElem= 3 (array[2]): 0x22ff58 *minElem: 3 NEW *minElem= 2 (array[3]): 0x22ff5c *minElem: 2 After loop on startScan=0 0x22ff58 0x22ff54 0x22ff50 0x22ff5c 2 3 10 7 OUTER LOOP: minElem: 0x22ff54 *minElem: 3 (array[2]): 0x22ff50 *minElem: 3 (array[3]): 0x22ff5c *minElem: 3 After loop on startScan=1 0x22ff58 0x22ff54 0x22ff50 0x22ff5c 2 3 10 7 OUTER LOOP: minElem: 0x22ff50 *minElem: 10 (array[3]): 0x22ff5c *minElem: 10 NEW *minElem= 7 After loop on startScan=2 0x22ff58 0x22ff54 0x22ff5c 0x22ff50 2 3 7 10 The donations, sorted in ascending order are: 2 3 7 10 The donations, in their original order are: 10 3 2 7

85 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 85 Array of Pointers startScan=0: smallest number initialized to 10, then compared to 3,2 and 7. 2 is the smallest. Swap address that point to 2 and 10 startscan=1: smallest number initialized to 3, compare to 10 and 7. 3 is smaller than both so no change in pointers startScan=2: smallest number initialized to 10, compare to 7. 7 is smaller no swap pointers of 10 and 7 103275058545c103275850545c10327585c5450 58545c5058545c5058545c initial setup after startScan=0 after startScan=2 (and 1)  array  arrPtr

86 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 86 Returning Pointers from Functions There are two ways you can return a pointer to a primitive variable type (int, double, etc.) from a function Dynamically Allocated Memory Global Pointer #include using namespace std; int* test(); int main(){ int *iptr; iptr = test(); cout<<"*iptr: "<<*iptr<<endl; } int* test(){ int w=10; int *x = new int; *x = w; return x; } #include using namespace std; int* test(); int z=7; int *x=&z; int main(){ int *iptr; iptr = test(); cout<<"*iptr: "<<*iptr<<endl; } int* test(){ int w=10; *x = w; return x; }

87 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 87 Dynamically Growing Arrays Write a program that starts out with an integer array of maximum size 5 Values for the array are entered at the keyboard, one by one. When the number of values entered exceeds maximum size, create a new array with twice the maximum size, move the old values into the new array, save the last value entered and continue prompting for more values If the new maximum size is exceeded, follow the same steps as before

88 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 88 Dynamically Growing Arrays #include using namespace std; int main(){ int *iptr, *iptrold; int num, maxsize=5; iptr = new int[maxsize]; int count=0; cout<<"\nEnter a number: "; cin>>num; while ( !cin.eof() ) { if (count < maxsize) { iptr[count] = num; count++; } else { cout<<"\nReached maxsize"<<endl; iptrold=iptr; iptr = new int[maxsize*2]; for (int i=0;i<maxsize;i++) *(iptr+i) = *(iptrold+i); iptrold=0; iptr[count] = num; count++; maxsize=maxsize*2; } cout<<"\nEnter a number: "; cin>>num; } for (int i=0;i<maxsize;i++) { cout<<"iptr["<<i<<"]="<<iptr[i]<<endl; }

89 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 89 Dynamically Growing Arrays Initialize two pointers int *iptr, *iptrold; This code adds a new value to the array pointed to by iptr if (count < maxsize) { iptr[count] = num; count++; }

90 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 90 Dynamically Growing Arrays When the current size is exceeded –set iptrold to point to iptr –create a new array twice the size of maxsize pointed to by iptr –copy the values from iptrold to iptr –have iptrold point to null –add the last value read in to the new array –increase count by 1 –double maxsize else { cout<<"\nReached maxsize"<<endl; iptrold=iptr; iptr = new int[maxsize*2]; for (int i=0;i<maxsize;i++) *(iptr+i) = *(iptrold+i); iptrold=0; iptr[count] = num; count++; maxsize=maxsize*2; }

91 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 91 Dynamically Growing Arrays Enter a number: 1 Enter a number: 2 Enter a number: 3 Enter a number: 4 Enter a number: 5 Enter a number: 6 Reached maxsize maxsize: 5 Enter a number: 7 Enter a number: 8 Enter a number: 9 Enter a number: 10 Enter a number: 11 Reached maxsize maxsize: 10 Enter a number: 22 Enter a number: 23 Enter a number: ^Z iptr[0]=1 iptr[1]=2 iptr[2]=3 iptr[3]=4 iptr[4]=5 iptr[5]=6 iptr[6]=7 iptr[7]=8 iptr[8]=9 iptr[9]=10 iptr[10]=11 iptr[11]=12 iptr[12]=13 iptr[13]=14 iptr[14]=15 iptr[15]=16 iptr[16]=17 iptr[17]=18 iptr[18]=19 iptr[19]=20 iptr[20]=21 iptr[21]=22 iptr[22]=23 maxsize: 10 Enter a number: 12 Enter a number: 13 Enter a number: 14 Enter a number: 15 Enter a number: 16 Enter a number: 17 Enter a number: 18 Enter a number: 19 Enter a number: 20 Enter a number: 21 Reached maxsize maxsize: 20 iptr[23]=0 iptr[24]=0 iptr[25]=0 iptr[26]=0 iptr[27]=0 iptr[28]=0 iptr[29]=0 iptr[30]=0 iptr[31]=0 iptr[32]=0 iptr[33]=0 iptr[34]=0 iptr[35]=0 iptr[36]=0 iptr[37]=0 iptr[38]=0 iptr[39]=0

92 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 10: Pointers


Download ppt "Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy."

Similar presentations


Ads by Google