Chapter 10 Pointers Starting Out with C Early

  • Slides: 92
Download presentation
Chapter 10: Pointers Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis,

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

10. 1 Pointers and the Address Operator • Each variable in a program is

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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -2

10. 2 Pointer Variables • Pointer variable (pointer): variable that holds an address •

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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -3

Something Like Pointers: Arrays • We have already worked with something similar to pointers,

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 show. Values function: show. Values(numbers, SIZE); Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 4

Something Like Pointers : Arrays The values parameter, in the show. Values function, points

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

Something Like Pointers: Reference Variables • We have also worked with something like pointers

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 get. Order(int &donuts) { cout << "How many doughnuts do you want? "; cin >> donuts; } • And we call it with this code: int jelly. Donuts; get. Order(jelly. Donuts); Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 6

Something Like Pointers: Reference Variables The donuts parameter, in the get. Order function, points

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

Pointer Variables • Pointer variables are yet another way using a memory address to

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. Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 8

Pointer Variables • Definition: int *intptr; • Read as: “intptr can hold the address

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; int* intptr; Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -9

Pointer Variables • Assignment: int num = 25; int *intptr; intptr = &num; •

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

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

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

The Indirection Operator • The indirection operator (*) dereferences a pointer. • It allows

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. Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 12

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

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

Reusing a pointer • When we apply the indirection operator to the pointer ptr,

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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 14

Reusing a pointer int main() { int x = 25, y = 50, z

Reusing a pointer int main() { int x = 25, y = 50, z = 75; int *ptr; // Three int variables // 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, ptr = &x; // Store the address of *ptr += 100; // Add 100 to the value ptr = &y; // Store the address of *ptr += 100; // Add 100 to the value ptr = &z; // Store the address of *ptr += 100; // Add 100 to the value and z. x in ptr. in x. y in ptr. in y. z in ptr. 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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 15

10. 3 The Relationship Between Arrays and Pointers • Array name is starting address

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

The Relationship Between Arrays & Pointers • Array name can be used as a

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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -17

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

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

Pointers in Expressions • Given: int vals[]={4, 7, 11}; int *valptr = vals; •

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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -19

Array Access Array elements can be accessed in many ways Array access method Example

Array Access Array elements can be accessed in many ways Array access method Example 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 3 rd element Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -20

Array Access • Array notation vals[i] is equivalent to the pointer notation *(vals +

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

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

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

Array Names vs Pointer Variables • The only difference between array names and pointer

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; Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 23

10. 4 Pointer Arithmetic Some arithmetic operators can be used with pointers: – Increment

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 - Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -24

Pointer Arithmetic Assume the variable definitions int vals[]={4, 7, 11}; int *valptr = vals;

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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -25

More on Pointer Arithmetic Assume the variable definitions: int vals[]={4, 7, 11}; int *valptr

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 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

More on Pointer Arithmetic 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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -27

More on Pointer Arithmetic Assume the variable definitions int vals[] = {4, 7, 11};

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 ints between valptr and vals Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -28

Pointer Arithmetic int vals[]={4, 7, 11}; int *valptr = vals; cout<<"nvalptr++: "<<valptr++; cout<<" *valptr:

Pointer Arithmetic int vals[]={4, 7, 11}; int *valptr = vals; cout<<"nvalptr++: "<<valptr++; cout<<" *valptr: "<<*valptr<<endl; valptr++: 0 x 22 ff 20 *valptr: 7 cout<<"valptr--: "<<valptr--; cout<<" *valptr: "<<*valptr<<endl; valptr--: 0 x 22 ff 24 *valptr: 4 *(valptr+2): 11 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+=2: 0 x 22 ff 28 valptr: 0 x 22 ff 28 vals: 0 x 22 ff 20 *valptr: 11 *vals: 4 valptr minus vals: 2 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 29

From Program 9 -9 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

Pointer Arithmetic - Summary Operation Example ++, -- int vals[]={4, 7, 11}; int *valptr

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

10. 5 Initializing Pointers • Can initialize to NULL or 0 (zero) int *ptr

10. 5 Initializing Pointers • Can initialize to NULL or 0 (zero) int *ptr = NULL; • Can initialize to addresses of other variables int num, *num. Ptr = &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). . . Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -32

10. 6 Comparing Pointers • Relational operators can be used to compare addresses in

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 (ptr 1 == ptr 2) // // if (*ptr 1 == *ptr 2) // // Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley compares addresses compares contents 10 -33

Comparing Pointers • Addresses grow larger for each subsequent element in an array a

Comparing Pointers • Addresses grow larger for each subsequent element in an array a r r a y [ 0 ] array[1] a r r a y [ 2 ] a r r a y [ 3 ] array[4] 0 x 5 A 00 0 x 5 A 04 0 x 5 A 08 0 x 5 A 0 C 0 x 5 A 10 (Addresses) Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 34

10. 7 Pointers as Function Parameters • A pointer can be used as a

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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -35

Pointers as Function Parameters • Requires: 1) asterisk * on parameter in prototype and

Pointers as Function Parameters • Requires: 1) asterisk * on parameter in prototype and heading void get. Num(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 get. Num(&num); num to get. Num // pass address of Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -36

Example #include <iostream> using namespace std; void swap(int*, int*); int main() { int x=5,

Example #include <iostream> 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; OUTPUT: } void swap(int* x, int* y) { int temp; temp = *x; *x = *y; *y = temp; } Before swap: x 5 y 10 After swap: x 10 y 5 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 37

When the getnumber function is called in line 15, the address of the number

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. (Program Continues) Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 38

cin>>input would store the value entered by the user in input as if the

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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 39

Pointers Variables to Arrays • To pass an array sales to a function using

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

Pointers Variables to Arrays FUNCTIONS void get. Sales(double* array, int size) { for (int

Pointers Variables to Arrays FUNCTIONS void get. Sales(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 total. Sales(double* array, int size) { double sum=0. 0; for (int count=0; count<size; count++) { sum += *array; array++; } return sum; } Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 41

10. 8 Pointers to Constants and Constant Pointers • Pointer to a constant: cannot

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? Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -42

Pointers to Constant • Must use const keyword in pointer definition: const double tax.

Pointers to Constant • Must use const keyword in pointer definition: const double tax. Rates[] = {0. 65, 0. 8, 0. 75}; const double *rate. Ptr; • Use const keyword for pointers in function headers to protect data from modification from within function Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -43

Pointers to Constants • Example: Suppose we have the following definitions: const int SIZE

Pointers to Constants • Example: Suppose we have the following definitions: const int SIZE = 6; const double pay. Rates[SIZE] = { 18. 55, 17. 45, 12. 85, 14. 97, 10. 35, 18. 89 }; double overtime. Rates[SIZE] = { 18. 55, 17. 45, 12. 85, 14. 97, 10. 35, 18. 89 }; • In this code, pay. Rates is an array of constant doubles and overtime. Rates is an array of non-constant doubles Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 44

Pointers to Constants • Suppose we wish to pass the pay. Rates array to

Pointers to Constants • Suppose we wish to pass the pay. Rates array to a function? Here's an example of how we can do it. FUNCTION PROTOTYPE: void display. Pay. Rates(const double *, int); CALL FROM MAIN: display. Pay. Rates(pay. Rates, SIZE); FUNCTION: void display. Pay. Rates(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. Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 45

Pointers to Constants • A function that uses a parameter that points to a

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

Pointer to Constant – What does the Definition Mean? Copyright © 2011 Pearson Education,

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

Pointer That Is a Constant Pointer Copyright © 2011 Pearson Education, Inc. Publishing as

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

Constant Pointers to Constants Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

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

Pointer Types • const double * rates A pointer to a const points to

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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 50

Constant Pointers • Defined with const keyword adjacent to variable name: int class. Size

Constant Pointers • Defined with const keyword adjacent to variable name: int class. Size = 24; int * const class. Ptr = &class. Size; • 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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -51

Constant Pointers • A constant pointer, ptr, is a pointer that is initialized with

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; Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 52

Regular Pointers int value 2= 987; int value 3=5678; int * ptr 2 =

Regular Pointers int value 2= 987; int value 3=5678; int * ptr 2 = &value 2; cout<<"n. Regular Pointern"; cout <<"value 2: "<<value 2<<" ptr 2: "<<ptr 2<<" *ptr 2: "<<*ptr 2<<endl; *ptr 2=12345; cout <<"value 2: "<<value 2<<" ptr 2: "<<ptr 2<<" *ptr 2: "<<*ptr 2<<endl; //LEGAL WITH REGUALR POINTER, CHANGE OF ADDRESS ptr 2= &value 3; cout <<"value 3: "<<value 3<<" ptr 2: "<<ptr 2<<" *ptr 2: "<<*ptr 2<<endl; Regular value 2: value 3: Pointer 987 ptr 2: 0 x 22 ff 0 c *ptr 2: 987 12345 ptr 2: 0 x 22 ff 0 c *ptr 2: 12345 5678 ptr 2: 0 x 22 ff 08 *ptr 2: 5678 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 53

Constant Pointers int value = 22; int value 4 = 99; int * const

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

Constant Pointers LEGAL: ILLEGAL: void set. To. Zero(int * const ptr) { *ptr =

Constant Pointers LEGAL: ILLEGAL: void set. To. Zero(int * const ptr) { *ptr = 0; } void set. To. Zero(int * const ptr) { ptr = 0; } • 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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 55

Pointer to a Constant int value 6 = 666; int value 7 = 777;

Pointer to a Constant int value 6 = 666; int value 7 = 777; const int * ptr 6 = &value 6; cout<<"n. Pointer to a Constantn"; cout <<"value 6: "<<value 6<<" ptr 6: "<<ptr 6<<" *ptr 6: "<<*ptr 6<<endl; value 6=6666; cout <<"value 6: "<<value 6<<" ptr 6: "<<ptr 6<<" *ptr 6: "<<*ptr 6<<endl; ptr 6=&value 7; cout <<"value 7: "<<value 7<<" ptr 6: "<<ptr 6<<" *ptr 6: "<<*ptr 6<<endl; //CAN NOT BE DONE // *ptr 6=6543; Pointer value 6: value 7: to a Constant 666 ptr 6: 0 x 22 ff 74 *ptr 6: 6666 777 ptr 6: 0 x 22 ff 70 *ptr 6: 777 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 56

Constant Pointer to a Constant int value 5 = 55; int value 12 =

Constant Pointer to a Constant int value 5 = 55; int value 12 = 1212; const int * const ptr 5 = &value 5; cout<<"n. Constant Pointer to a Constantn"; cout <<"value 5: "<<value 5<<" ptr 5: "<<ptr 5<<" *ptr 5: "<<*ptr 5<<endl; value 5=777; cout <<"value 5: "<<value 5<<" ptr 5: "<<ptr 5<<" *ptr 5: "<<*ptr 5<<endl; //CAN NOT PERFORM EITHER ONE OF THESE OPERATIONS // ptr 5 = &value 12; // *ptr 5=6543; Constant Pointer to a Constant value 5: 55 ptr 5: 0 x 22 ff 74 *ptr 5: 55 value 5: 777 ptr 5: 0 x 22 ff 74 *ptr 5: 777 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 57

Constant Pointers to Constants • A constant pointer to a constant is: – a

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; Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 58

10. 9 Dynamic Memory Allocation • Can allocate storage for a variable while program

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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -59

Dynamic Memory Allocation • Can also use new to allocate array: const int SIZE

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

Releasing Dynamic Memory • Use delete to free dynamic memory delete dptr; • Use

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! Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -61

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

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

Notice that in line 49 the value 0 is assigned to the sales pointer.

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. Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 63

Dangling Pointers and Memory Leaks • A pointer is dangling if it contains the

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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -64

10. 10 Returning Pointers from Functions • Pointer can be the return type of

10. 10 Returning Pointers from Functions • Pointer can be the return type of function int* new. Num(); • 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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -65

Returning Pointers from Functions #include <iostream> using namespace std; char *find. Null(char*); int main(){

Returning Pointers from Functions #include <iostream> using namespace std; char *find. Null(char*); int main(){ char *s = {"Ira Rudowsky"}; cout<<“String at null is ["<<(find. Null(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 *find. Null(char *str) { int count=0; cout<<"count: "<<count<<" "; char *ptr = str; while (*ptr !='') { cout<<" *ptr: "<<*ptr<<" ptr: "<<ptr<<" &ptr: "<<&ptr<<endl; count++; ptr++; cout<<"count: "<<count<<" "; } cout<<endl; return ptr; } Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 66

Returning Pointers from Functions OUTPUT: count: count: count: count: String 0 1 2 3

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

Returning Pointers from Functions #include <iostream> #include <cstdlib> // For rand srand #include <ctime>

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

Exercise • Complete the following program skeleton. The program asks for a value in

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 <iostream> #include <iomanip> 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<<“n. Value in centimeters: "<<measurement<<endl; return 0; } FUNCTION convert Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 69

10. 11 Pointers to Class Objects and Structures • Can create pointers to objects

10. 11 Pointers to Class Objects and Structures • Can create pointers to objects and structure variables struct Student {…}; class Square {…}; Student stu 1; Student *stu. Ptr = &stu 1; Square sq 1[4]; Square *square. Ptr = &sq 1[0]; • Need () when using * and. (*stu. Ptr). student. ID = 12204; as the dot selector has higher priority than the * operator Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -70

Structure Pointer Operator • Simpler notation than (*ptr). member • Use the form ptr->member:

Structure Pointer Operator • Simpler notation than (*ptr). member • Use the form ptr->member: stu. Ptr->student. ID = 12204; square. Ptr->set. Side(14); in place of the form (*ptr). member: (*stu. Ptr). student. ID = 12204; (*square. Ptr). set. Side(14); Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -71

Dynamic Memory with Objects • Can allocate dynamic structure variables and objects using pointers:

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

Pointers to Class Objects as Function Parameters • Pointers to structures and class variables

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 Dynamic. Allocation. Objects. As. Func. Parms Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -73

Stopping Memory Leaks • When using DAM, make sure that each call to new

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 Memory. Leaks Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -74

10. 12 Selecting Members of Objects Situation: A structure/object contains a pointer as a

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 Grade. List { string course. Num; int * grades; } Grade. List test 1, *test. Ptr = &test 1; Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -75

Selecting Members of Objects Expression Meaning test. Ptr->grades Access the grades pointer in test

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

Selecting Members of Objects struct Grade. Info { char name[25]; int *test. Scores; double

Selecting Members of Objects struct Grade. Info { char name[25]; int *test. Scores; double average; } Grade. Info student 1; Displays value pointed to by the test. Scores member cout<<*student 1. test. Scores; Grade. Info *st. Ptr; //pointer to structure cout<<*st. Ptr->test. Scores; st. Ptr->test. Scores <--> (*st. Ptr). test. Scores *st. Ptr->test. Scores <--> *(*st. Ptr). test. Scores Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -77

#include <iostream> //Project - Pointer. To. Structures using namespace std; class Grade. Info {

#include <iostream> //Project - Pointer. To. Structures using namespace std; class Grade. Info { public: char name[25]; int *test. Scores; double average; Grade. Info (){ test. Scores = new int; } }; int main(){ Grade. Info student 1; Grade. Info *gr. Ptr = &student 1; *student 1. test. Scores = 98; cout<<"<<*student 1. test. Scores<<endl; cout<<"&student 1 "<<&student 1<<endl; cout<<"gr. Ptr "<<gr. Ptr<<endl; cout<<"&gr. Ptr "<<&gr. Ptr<<endl; cout<<"student 1. test. Scores "<<student 1. test. Scores<<endl; cout<<"(*(&student 1). test. Scores "<<(*(&student 1)). test. Scores<<endl; *(*gr. Ptr). test. Scores=90; cout<<"gr. Ptr "<<*(*gr. Ptr). test. Scores<<endl; cout<<"gr. Ptr->test. Scores "<<gr. Ptr->test. Scores<< " *(gr. Ptr). test. Scores "<<(*gr. Ptr). test. Scores<<endl; cout<<"*gr. Ptr->test. Scores "<<*gr. Ptr->test. Scores<< " *(*gr. Ptr). test. Scores "<<*(*gr. Ptr). test. Scores<<endl; return 0; } Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -78

*student 1. test. Scores 98 &student 1 0 x 22 ff 40 gr. Ptr

*student 1. test. Scores 98 &student 1 0 x 22 ff 40 gr. Ptr 0 x 22 ff 40 &gr. Ptr 0 x 22 ff 3 c student 1. test. Scores 0 x 3 e 2498 (*(&student 1). test. Scores 0 x 3 e 2498 gr. Ptr 90 gr. Ptr->test. Scores 0 x 3 e 2498 *(gr. Ptr). test. Scores 0 x 3 e 2498 *gr. Ptr->test. Scores 90 *(*gr. Ptr). test. Scores 90 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 -79

Arrays of Pointers • This example will have an array donations of unsorted integers

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 arr. Ptr • We will then sort arr. Ptr based on the value stored and then display the sorted values without actually sorting the array donations Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 80

#include <iostream> using namespace std; Arrays of Pointers void arr. Select. Sort(int *[], int);

#include <iostream> using namespace std; Arrays of Pointers void arr. Select. Sort(int *[], int); void show. Array(int [], int); void show. Arr. Ptr(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, int *arr. Ptr[NUM_DONATIONS]; // An array of pointers to int. 5, 100, 15, 10, 5, 10 }; // Each element of arr. Ptr is a pointer to an int element in donations for (int count = 0; count < NUM_DONATIONS; count++) arr. Ptr[count] = &donations[count]; arr. Select. Sort(arr. Ptr, 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"; show. Arr. Ptr(arr. Ptr, NUM_DONATIONS); // Display the donations in their original order. cout << "The donations, in their original order are: n"; show. Array(donations, NUM_DONATIONS); return 0; } Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 81

//******************************** // Definition of function arr. Select. Sort. * // This function performs an

//******************************** // Definition of function arr. Select. Sort. * // 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 arr. Select. Sort(int *array[], int size) { int start. Scan, min. Index; int *min. Elem; for (start. Scan = 0; start. Scan < (size - 1); start. Scan++) { min. Index = start. Scan; min. Elem = array[start. Scan]; cout<<"OUTER LOOP: min. Elem: "<<min. Elem<<" *min. Elem: "<<*min. Elem<<endl; for(int index = start. Scan + 1; index < size; index++) { cout<<" (array["<<index<<"]): "<<(array[index])<<" *min. Elem: "<<*min. Elem<<endl; if (*(array[index]) < *min. Elem) { min. Elem = array[index]; min. Index = index; cout<<"NEW min. Elem= "<<*min. Elem<<endl; } } array[min. Index] = array[start. Scan]; array[start. Scan] = min. Elem; cout<<"After loop on start. Scan="<<start. Scan<<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; } Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley } CIS 15 Pointer Arithmetic 82

Arrays of Pointers //******************************* // Definition of function show. Array. * // This function

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

Arrays of Pointers arr. Ptr[0]: 0 x 22 ff 50 *arr. Ptr[0]: 10 &donations[0]:

Arrays of Pointers arr. Ptr[0]: 0 x 22 ff 50 *arr. Ptr[0]: 10 &donations[0]: 10 arr. Ptr[1]: 0 x 22 ff 54 *arr. Ptr[1]: 3 &donations[1]: 3 arr. Ptr[2]: 0 x 22 ff 58 *arr. Ptr[2]: 2 &donations[2]: 2 arr. Ptr[3]: 0 x 22 ff 5 c *arr. Ptr[3]: 7 &donations[3]: 7 OUTER LOOP: min. Elem: 0 x 22 ff 50 *min. Elem: 10 (array[1]): 0 x 22 ff 54 *min. Elem: 10 NEW *min. Elem= 3 (array[2]): 0 x 22 ff 58 *min. Elem: 3 NEW *min. Elem= 2 (array[3]): 0 x 22 ff 5 c *min. Elem: 2 After loop on start. Scan=0 0 x 22 ff 58 0 x 22 ff 54 0 x 22 ff 50 0 x 22 ff 5 c 2 3 10 7 OUTER LOOP: min. Elem: 0 x 22 ff 54 *min. Elem: 3 (array[2]): 0 x 22 ff 50 *min. Elem: 3 (array[3]): 0 x 22 ff 5 c *min. Elem: 3 After loop on start. Scan=1 0 x 22 ff 58 0 x 22 ff 54 0 x 22 ff 50 0 x 22 ff 5 c 2 3 10 7 OUTER LOOP: min. Elem: 0 x 22 ff 50 *min. Elem: 10 (array[3]): 0 x 22 ff 5 c *min. Elem: 10 NEW *min. Elem= 7 After loop on start. Scan=2 0 x 22 ff 58 0 x 22 ff 54 0 x 22 ff 5 c 0 x 22 ff 50 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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 84

Array of Pointers 50 54 58 5 c 10 10 10 3 2 7

Array of Pointers 50 54 58 5 c 10 10 10 3 2 7 50 54 58 5 c initial setup 3 2 7 58 54 50 5 c 3 2 7 array 58 54 5 c 50 arr. Ptr after start. Scan=0 after start. Scan=2 (and 1) • start. Scan=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 • start. Scan=2: smallest number initialized to 10, compare to 7. 7 is smaller no swap pointers of 10 and 7 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 85

Returning Pointers from Functions • There are two ways you can return a pointer

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 #include <iostream> 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; } Global Pointer #include <iostream> 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; } Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 86

Dynamically Growing Arrays • Write a program that starts out with an integer array

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 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 87

Dynamically Growing Arrays #include <iostream> using namespace std; else { cout<<"n. Reached maxsize"<<endl; iptrold=iptr;

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

Dynamically Growing Arrays • Initialize two pointers int *iptr, *iptrold; • This code adds

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++; } Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 89

Dynamically Growing Arrays • When the current size is exceeded – – – –

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<<"n. Reached 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; } Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 90

Dynamically Growing Arrays Enter a number: 1 Enter a number: 2 Enter a number:

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 maxsize: 10 Enter a number: 22 Enter a number: 12 Enter a number: 23 Enter a number: 13 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 Enter a number: 14 Enter a number: 15 Enter a number: 16 Enter a number: 17 Enter a number: 18 Enter a number: 19 Reached maxsize: 5 Enter a number: 20 Enter a number: 7 Reached maxsize: 20 Enter a number: 8 Enter a number: 21 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 Enter a number: 9 Enter a number: 10 Enter a number: 11 Reached maxsize: 10 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley CIS 15 Pointer Arithmetic 91

Chapter 10: Pointers Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis,

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