xiaoyan li, 2007 1 csc211 data structures lectures 6/7 pointers and dynamic arrays instructor: prof....

56
Xiaoyan Li, 2007 Xiaoyan Li, 2007 1 CSC211 Data Structures Lectures 6/7 Lectures 6/7 Pointers and Dynamic Pointers and Dynamic Arrays Arrays Instructor: Prof. Xiaoyan Li Instructor: Prof. Xiaoyan Li Department of Computer Science Department of Computer Science Mount Holyoke College Mount Holyoke College

Upload: lesley-harcrow

Post on 14-Dec-2015

230 views

Category:

Documents


2 download

TRANSCRIPT

Xiaoyan Li, 2007Xiaoyan Li, 2007 11

CSC211 Data Structures CSC211 Data Structures

Lectures 6/7Lectures 6/7Pointers and Dynamic ArraysPointers and Dynamic Arrays

Instructor: Prof. Xiaoyan LiInstructor: Prof. Xiaoyan LiDepartment of Computer Science Department of Computer Science

Mount Holyoke CollegeMount Holyoke College

Xiaoyan Li, 2007Xiaoyan Li, 2007 22

About Quiz 2 from Lecture 5About Quiz 2 from Lecture 5

bool bag::erase_one(const int& target)bool bag::erase_one(const int& target){if (count(target) = = 0) return false;{if (count(target) = = 0) return false; else {else {

for (int i=0; i<used; i++){for (int i=0; i<used; i++){if (data[i] = = target){if (data[i] = = target){ data[i] = = data[used-1];data[i] = = data[used-1]; used--;used--; return true;return true;}}

}}}}

}}

Q1: data[i] = data[used];Q1: data[i] = data[used];

Q2: data[target] = data[used-1];Q2: data[target] = data[used-1];

Xiaoyan Li, 2007Xiaoyan Li, 2007 33

Review: (Lecture 5)Review: (Lecture 5)

Bag class definition/implementation detailsBag class definition/implementation details Inline functionsInline functions

constructor, sizeconstructor, size Other basic functions Other basic functions

insert, erase_one, erase, countinsert, erase_one, erase, count More advanced functions More advanced functions

operators +, +=, -operators +, +=, -

Time Analysis Time Analysis Big-O Big-O

Introduction to sequence Introduction to sequence

Xiaoyan Li, 2007Xiaoyan Li, 2007 44

Review: Append Operator +=Review: Append Operator +=

void bag::operator+=(const bag& addend)// Precondition: size( ) + addend.size( ) <= CAPACITY.// Postcondition: Each item in addend has been added to this bag.// Library facilities used: algorithm, cassert{

assert(size( ) + addend.size( ) <= CAPACITY);

copy(addend.data, addend.data + addend.used, data + used);used += addend.used;

}

// copy (<beginning location>, ending location>, <destination>);

Xiaoyan Li, 2007Xiaoyan Li, 2007 55

Review: Union Operator +Review: Union Operator +

// NONMEMBER FUNCTION for the bag class:bag operator+(const bag& b1, const bag& b2)// Precondition: b1.size( ) + b2.size( ) <= bag::CAPACITY.// Postcondition: The bag returned is the union of b1 and b2.// Library facilities used: cassert{ bag answer;

assert(b1.size( ) + b2.size( ) <= bag::CAPACITY);

answer += b1; answer += b2; return answer;}

// calling program: c =a+b; // Question : what happens if you call a =a+b ?// Question : why operator+ is a nonmember function ?

Xiaoyan Li, 2007Xiaoyan Li, 2007 66

Review: Subtract Operator -Review: Subtract Operator -

// NONMEMBER friend FUNCTION for the bag class:bag operator-(const bag& b1, const bag& b2)// Postcondition: For two bags b1 and b2, the bag x-y contains all the

items of x, with any items from y removed{

size_t index;bag answer(b1); // copy constructorsize_t size2 = b2.size(); // use member function size for (index = 0; index < size2; ++index){

int target = b2.data[index]; // use private member variableif (answer.count(target) ) // use function count

answer.erase_one(target); // use function erase_one}return answer;

}

Xiaoyan Li, 2007Xiaoyan Li, 2007 77

Why Friend functions?Why Friend functions?

A friend function can access all private A friend function can access all private member variables of a class. member variables of a class.

A special feature in C++ (not supported in A special feature in C++ (not supported in java or C#)java or C#)

Xiaoyan Li, 2007Xiaoyan Li, 2007 88

Advantages of Friend functions?Advantages of Friend functions?

Provide a degree of freedom in the interface design Provide a degree of freedom in the interface design optionsoptions Choose between member functions (x.f()) and Choose between member functions (x.f()) and

friend functions (f(x))friend functions (f(x)) Having a public get() and set() member function Having a public get() and set() member function

for a private datum is OK only when the private for a private datum is OK only when the private datum "makes sense" from outside the class. In datum "makes sense" from outside the class. In many cases, they are almost as bad as public data: many cases, they are almost as bad as public data: they hide (only) the they hide (only) the namename of the private datum, of the private datum, but they don't hide the existence of the private but they don't hide the existence of the private datumdatum. .

Should my class declare a member function or a Should my class declare a member function or a friend function?friend function?

Xiaoyan Li, 2007Xiaoyan Li, 2007 99

Advantages of Friend functions?Advantages of Friend functions?

Provide a degree of freedom in the interface design optionsProvide a degree of freedom in the interface design options Choose between member functions (x.f()) and friend Choose between member functions (x.f()) and friend

functions (f(x))functions (f(x)) Having a public get() and set() member function for a Having a public get() and set() member function for a

private datum is OK only when the private datum "makes private datum is OK only when the private datum "makes sense" from outside the class. In many cases, they are sense" from outside the class. In many cases, they are almost as bad as public data: they hide (only) the almost as bad as public data: they hide (only) the namename of of the private datum, but they don't hide the existence of the the private datum, but they don't hide the existence of the private datumprivate datum. .

Should my class declare a member function or a friend Should my class declare a member function or a friend function?function? Use a member when you can, and a friend when you have Use a member when you can, and a friend when you have

to. (to. (Use it wiselyUse it wisely! Do not make too many friends ! Do not make too many friends ))

Xiaoyan Li, 2007Xiaoyan Li, 2007 1010

Why Pointers and Dynamic MemoryWhy Pointers and Dynamic Memory

Limitation of our bag classLimitation of our bag class

class bag{public: static const size_t CAPACITY = 20; ...private: int data[CAPACITY]; size_t used;};

Xiaoyan Li, 2007Xiaoyan Li, 2007 1111

Why Pointers and Dynamic MemoryWhy Pointers and Dynamic Memory

Limitation of our bag classLimitation of our bag class bag::CAPACITY constant determines the capacity of bag::CAPACITY constant determines the capacity of

every bagevery bag wasteful (if too big) and hard to reuse (if too small)wasteful (if too big) and hard to reuse (if too small)

need to change source code and recompileneed to change source code and recompile

Solution: Solution: provide control over size in provide control over size in running timerunning time <= dynamic arrays<= dynamic arrays <= pointers and dynamic memory<= pointers and dynamic memory

Xiaoyan Li, 2007Xiaoyan Li, 2007 1212

Outline (Reading Ch 4.1 – 4.2)Outline (Reading Ch 4.1 – 4.2)

PointersPointers *(asterisk) and &(ampersand) operators*(asterisk) and &(ampersand) operators

Dynamic Variables and Dynamic Variables and newnew Operator Operator Dynamic Arrays and Dynamic ObjectsDynamic Arrays and Dynamic Objects Stack (local) vs. heap (dynamic) memoryStack (local) vs. heap (dynamic) memory

Garbage Collection and Garbage Collection and deletedelete Operator Operator Parameters revisitedParameters revisited

Pointers and Arrays as ParametersPointers and Arrays as Parameters

Xiaoyan Li, 2007Xiaoyan Li, 2007 1313

Pointer VariablePointer Variable

First let’s have a look at local variablesFirst let’s have a look at local variables

Q: What’s the value of i? Q: What’s the value of i?

??900900

904904

908908

912912

916916

……

int i; ii

By this declaration, a cell of By this declaration, a cell of 4 adjacent bytes (in some 4 adjacent bytes (in some machines) are allocated in machines) are allocated in the local memory (called the local memory (called stack memorystack memory)) Address 9## is just for Address 9## is just for

illustration.illustration.Real address may have Real address may have 64 bits64 bits

Xiaoyan Li, 2007Xiaoyan Li, 2007 1414

Pointer Variable Pointer Variable

First let’s have a look at local variablesFirst let’s have a look at local variables

Q: How to get the address?Q: How to get the address? Q: What is the binary representation of 42? Q: What is the binary representation of 42?

4242900900

904904

908908

912912

916916

……

int i;

i = 42; ii

The assignment put number The assignment put number 42 in the cell. The memory 42 in the cell. The memory address of the 1address of the 1stst byte is the byte is the address of the variableaddress of the variable i i

– – the the pointerpointer to i to i

Xiaoyan Li, 2007Xiaoyan Li, 2007 1515

Pointer Variable Pointer Variable

First let’s have a look at local variablesFirst let’s have a look at local variables

Q: Where can we store &i? Q: Where can we store &i?

4242900900

904904

908908

912912

916916

……

int i;

i = 42;

cout << &i;

ii

& (ampersand) operator& (ampersand) operator- “ “address of address of ” ” operatoroperator- &i is 900 !&i is 900 !

-Note: two meanings of &Note: two meanings of &

Xiaoyan Li, 2007Xiaoyan Li, 2007 1616

Pointer Variable Pointer Variable

The memory address can be stored a special The memory address can be stored a special pointer variablepointer variable

Q: How to point i_ptr to i?Q: How to point i_ptr to i?

4242

??

900900

904904

908908

912912

916916

……

int i=42;

int *i_ptr;

ii

i_ptri_ptr

1.1. the type of the data that the type of the data that the pointer points to: intthe pointer points to: int

2.2. an asterisk (*)an asterisk (*)3.3. the name of the newly the name of the newly

declared pointer: i_ptrdeclared pointer: i_ptr

Xiaoyan Li, 2007Xiaoyan Li, 2007 1717

Pointer Variable Pointer Variable

Assign the address of i to i_ptrAssign the address of i to i_ptr4242

??

900900

904904

908908

912912

916916

……

int i=42;

int *i_ptr;

i_ptr = &i;

ii

i_ptri_ptr

What are the results ofWhat are the results of- cout << i; cout << i; - cout << i_ptr;cout << i_ptr;- cout << &i_ptr;cout << &i_ptr;

Xiaoyan Li, 2007Xiaoyan Li, 2007 1818

Pointer Variable Pointer Variable

The i_ptr holds the address of an integer, The i_ptr holds the address of an integer, not the integer itselfnot the integer itself 4242

900900

900900

904904

908908

912912

916916

……

int i=42;

int *i_ptr;

i_ptr = &i;

ii

i_ptri_ptr

Two ways to refer to iTwo ways to refer to i- cout << i; cout << i; - cout << *i_ptr;cout << *i_ptr; - - dereferencing operatordereferencing operator * * - two meanings of *- two meanings of *

Xiaoyan Li, 2007Xiaoyan Li, 2007 1919

Operators * and &Operators * and &

Operator *Operator * Pointer declarationPointer declaration

int *i_ptr;int *i_ptr; dereferencing operatordereferencing operator

cout << *i_ptr;cout << *i_ptr;

Two different Two different meanings!meanings!

Operator &Operator & Reference parameter Reference parameter

void funct(int& i);void funct(int& i); ““address of ” operatoraddress of ” operator

i_ptr = &i;i_ptr = &i;

Xiaoyan Li, 2007Xiaoyan Li, 2007 2020

Syntax and Naming IssuesSyntax and Naming Issues

How to declare two pointers in a lineHow to declare two pointers in a linechar *c1_ptr, *c2_ptr;char *c1_ptr, *c2_ptr; instead ofinstead of

char* c1_ptr, c2_ptr;char* c1_ptr, c2_ptr;

For clarity, use For clarity, use _ptr_ptr or or cursorcursor for pointer for pointer variablesvariables

Xiaoyan Li, 2007Xiaoyan Li, 2007 2121

Assignment Operators with PointersAssignment Operators with Pointers

p2 = p1p2 = p1

int i = 42;

int *p1, *p2;

p1 = &i;

p2 = p1;

4242 ii900900

address value name address value name

?? p1p1904904 ?? p2p2908908

Both p1 and p2 point to the same integerBoth p1 and p2 point to the same integer

900900 p1p1904904 900900 p2p2908908

4242

??

??

900900

904904

908908

912912

916916

……

ii

p1p1

p2p2

900900

900900

Xiaoyan Li, 2007Xiaoyan Li, 2007 2222

Assignment Operators with PointersAssignment Operators with Pointers

**p2 = *p1p2 = *p1

int i = 42;

int *p1, *p2;

p1 = &i;

*p2 = *p1;

4242 ii900900

address value name address value name

?? p1p1904904 ?? p2p2908908

p2 doesn’t point to anywhere, so assigning p2 doesn’t point to anywhere, so assigning value to *p2 will cause a running time error!value to *p2 will cause a running time error!

900900 p1p1904904

4242

??

??

900900

904904

908908

912912

916916

……

ii

p1p1

p2p2

900900

XX

Xiaoyan Li, 2007Xiaoyan Li, 2007 2323

?? p1p1908908 900900 p1p1908908 ?? p2p2912912 904904 p2p2912912

Assignment Operators with PointersAssignment Operators with Pointers

**p2 = *p1p2 = *p1

int i = 42;

int j = 20;

int *p1, *p2;

p1 = &i;

p2 = &j;

*p2 = *p1;

4242 ii900900

Both i (*p1) and j (*p2) will have the same Both i (*p1) and j (*p2) will have the same integer valuesinteger values

4242

2020

??

??

900900

904904

908908

912912

916916

……

ii

jj

p1p1

p2p2

900900

9049042020 jj904904 4242 jj904904

4242

Xiaoyan Li, 2007Xiaoyan Li, 2007 2424

Outline (Reading Ch 4.1 – 4.2)Outline (Reading Ch 4.1 – 4.2)

PointersPointers *(asterisk) and &(ampersand) operators*(asterisk) and &(ampersand) operators

Dynamic Variables and Dynamic Variables and newnew Operator Operator Dynamic Arrays and Dynamic ObjectsDynamic Arrays and Dynamic Objects Stack (local) vs. heap (dynamic) memoryStack (local) vs. heap (dynamic) memory

Garbage Collection and Garbage Collection and deletedelete Operator Operator Parameters revisitedParameters revisited

Pointers and Arrays as ParametersPointers and Arrays as Parameters

Xiaoyan Li, 2007Xiaoyan Li, 2007 2525

Dynamic VariablesDynamic Variables

We cannot use a pointer if not initializedWe cannot use a pointer if not initialized need to point to a declared variableneed to point to a declared variable

How to use a pointer without connecting How to use a pointer without connecting with a declared ordinary variable?with a declared ordinary variable? Solution: Solution: Dynamic (allocated) variablesDynamic (allocated) variables

not declared, therefore no identifiernot declared, therefore no identifier created during execution created during execution

Real power of pointers is with dynamic Real power of pointers is with dynamic variablesvariables

Xiaoyan Li, 2007Xiaoyan Li, 2007 2626

The new OperatorThe new Operator

allocates memory and return a pointerallocates memory and return a pointer

?? p1p1900900int *p1;

p1 = new int;

*p1 = 20;

?? ??1050010500

- p1 points to a dynamic integer variable - p1 points to a dynamic integer variable without any identifier (name) without any identifier (name)

- dynamic memory comes from the - dynamic memory comes from the programs’ programs’ heapheap (free store) (free store)

2020 ??1050010500

??900900

904904

908908

……

……

1049210492

1049610496

1050010500

p1p1

??

1050010500

2020

Xiaoyan Li, 2007Xiaoyan Li, 2007 2727

Dynamic ArraysDynamic Arrays

new can allocate an entire array all at oncenew can allocate an entire array all at once

?? p1p1900900int *p1;

p1 = new int[4];

p1[2] = 20;

cout<<*(p1+2);1048810488

- p1 points to 1st entry of dynamic array- p1 points to 1st entry of dynamic array

- number of entries in a pair of sq. brackets number of entries in a pair of sq. brackets

- two ways to access p1 (array or pointer) two ways to access p1 (array or pointer)

??900900

904904

908908

……

……

1048810488

1049210492

1049610496

1050010500

p1p1

??

1048810488

2020

2020

Xiaoyan Li, 2007Xiaoyan Li, 2007 2828

Accessing Dynamic ArrayAccessing Dynamic Array

Use array notationUse array notation the 1the 1stst entry entry

p1[0] = 18;p1[0] = 18; the 3the 3rdrd entry entry

p1[2] = 20;p1[2] = 20; the ith entrythe ith entry

p1[i-1] = 19;p1[i-1] = 19;

Use pointer notationUse pointer notation the 1the 1stst entry entry

*p1 = 18;*p1 = 18; the 3the 3rdrd entry entry

*(p1+2) = 20;*(p1+2) = 20; the ith entrythe ith entry

*(p1+i-1) = 19;*(p1+i-1) = 19;

Xiaoyan Li, 2007Xiaoyan Li, 2007 2929

Dynamic Array Example: (2 minutes)Dynamic Array Example: (2 minutes)

A program read ages A program read ages of each of MHC of each of MHC classes, with varying classes, with varying sizes, calculate the sizes, calculate the average, and then average, and then print out the print out the average. – average. – think think about the variables about the variables needed.needed.

size_t size;

int *ages;

float average;

cin >> size;

ages = new int[size];

// input ages of all students

// calculate average

// print average

Xiaoyan Li, 2007Xiaoyan Li, 2007 3030

Dynamic Objects of a classDynamic Objects of a class

new can also allocate a dynamic objectnew can also allocate a dynamic object

?? p1p1900900point *p1;

p1 = new point(1.0, 2.0);

cout<< (*p1).get_x();

cout<< p1->get_x();

- p1 points to dynamic object without name- p1 points to dynamic object without name

- parameters can be used as in declarationparameters can be used as in declaration

- two ways to access p1 (* and ->)two ways to access p1 (* and ->)

??900900

904904

908908

……

……

1048810488

1049210492

1049610496

1050010500

p1p1

??

1049610496

1.01.0

2.02.0

1049610496 1.01.0 2.02.0

Xiaoyan Li, 2007Xiaoyan Li, 2007 3131

Array of Dynamic Objects of a classArray of Dynamic Objects of a class

Q: Are the followings correct? Q: Are the followings correct? point3 demopoint3 demo Ten points with default coordinates?Ten points with default coordinates?

p1 = new point[10];p1 = new point[10]; Ten points with the same coordinates? Ten points with the same coordinates?

p1 = new point(1.0, 2.0)[10];p1 = new point(1.0, 2.0)[10]; Ten points on the x axis with interval 1?Ten points on the x axis with interval 1?

p1 = new point[10];p1 = new point[10]; for (i=0; i<10; i++) p1[i].set(i, 0);for (i=0; i<10; i++) p1[i].set(i, 0);

Assume we have a member functionAssume we have a member functionvoid point::set(double x_init, double y_init);void point::set(double x_init, double y_init);

VV

XX

VV

Xiaoyan Li, 2007Xiaoyan Li, 2007 3232

Programming Assignment 2Programming Assignment 2

Detailed guidelines online!Detailed guidelines online! In addition to your source files, also send in In addition to your source files, also send in

running results of the “exam” programs, running results of the “exam” programs, Cut & paste in a text fileCut & paste in a text file

The prototypes and pre/postconditions of The prototypes and pre/postconditions of functions in header files should not be functions in header files should not be changed. changed.

Due Oct. 1 (Monday)Due Oct. 1 (Monday)

Xiaoyan Li, 2007Xiaoyan Li, 2007 3333

Review: Pointers from Lecture 6Review: Pointers from Lecture 6

What is a pointer?What is a pointer? How to declare a pointer variable?How to declare a pointer variable? How to declare more pointers in one line?How to declare more pointers in one line? Operators & and * (two ways to refer to a Operators & and * (two ways to refer to a

variable)variable) Dynamic variables, dynamic objects, dynamic Dynamic variables, dynamic objects, dynamic

arrays? (two ways to refer to array elements.)arrays? (two ways to refer to array elements.) What is the function of operator “new”? What is the function of operator “new”?

Xiaoyan Li, 2007Xiaoyan Li, 2007 3434

Failure of the new OperatorFailure of the new Operator

Dynamic memory via new operator comes from heap of a Dynamic memory via new operator comes from heap of a program program ((i_ptr = new int; d_ptr = new double[20];

p_ptr = new point(1.0, 2.0);)) Heap size from several K to 1GB, however fixedHeap size from several K to 1GB, however fixed Could run out of room therefore cause a Could run out of room therefore cause a bad_allocbad_alloc

exception exception error message and program haltserror message and program halts

Good practice 1Good practice 1: document which functions use new: document which functions use new Good practice 2Good practice 2: garbage collection by : garbage collection by delete delete operatoroperator

Xiaoyan Li, 2007Xiaoyan Li, 2007 3535

Outline (Reading Ch 4.1 – 4.2)Outline (Reading Ch 4.1 – 4.2)

PointersPointers *(asterisk) and &(ampersand) operators*(asterisk) and &(ampersand) operators

Dynamic Variables and Dynamic Variables and newnew Operator Operator Dynamic Arrays and Dynamic ObjectsDynamic Arrays and Dynamic Objects Stack (local) vs. heap (dynamic) memoryStack (local) vs. heap (dynamic) memory

Garbage Collection and Garbage Collection and deletedelete Operator Operator Parameters revisitedParameters revisited

Pointers and Arrays as ParametersPointers and Arrays as Parameters

Xiaoyan Li, 2007Xiaoyan Li, 2007 3636

The delete OperatorThe delete Operator

Release any dynamic memory (heap Release any dynamic memory (heap memory) that is no longer neededmemory) that is no longer needed

int *i_ptr;

double *d_ptr;

point *p_ptr;

i_ptr = new int;

d_ptr = new double[20];

p_ptr = new point(1.0, 2.0);

… …

delete i_ptr;

delete [ ] d_ptr; // empty brackets

delete p_ptr;

Questions( true or false):

1. delete resets these pointers

2. delete removes dynamic objects pointed by the pointers

3. nothing happens to the pointers themselves

XX

VV

VV

Xiaoyan Li, 2007Xiaoyan Li, 2007 3737

Outline (Reading Ch 4.1 – 4.2) (Next Lecture)Outline (Reading Ch 4.1 – 4.2) (Next Lecture)

PointersPointers *(asterisk) and &(ampersand) operators*(asterisk) and &(ampersand) operators

Dynamic Variables and Dynamic Variables and newnew Operator Operator Dynamic Arrays and Dynamic ObjectsDynamic Arrays and Dynamic Objects Stack (local) vs. heap (dynamic) memoryStack (local) vs. heap (dynamic) memory

Garbage Collection and Garbage Collection and deletedelete Operator Operator Parameters revisitedParameters revisited

Pointers and Arrays as ParametersPointers and Arrays as Parameters

Xiaoyan Li, 2007Xiaoyan Li, 2007 3838

Pointers and Arrays as ParametersPointers and Arrays as Parameters

ValueValue parameters that are pointers parameters that are pointers ArrayArray parameters parameters Pointers and arrays as Pointers and arrays as constconst parameters parameters ReferenceReference parameters that are pointers parameters that are pointers

Xiaoyan Li, 2007Xiaoyan Li, 2007 3939

Value parameters that are pointersValue parameters that are pointers

Compare ordinary and pointer variablesCompare ordinary and pointer variablesvoid print_int_42(int i)

{

cout << i<<endl ;

i = 42 ;

cout << i <<endl;

}

void set_int_42(int* i_ptr)

{

cout << *i_ptr <<endl;

*i_ptr = 42 ;

cout << *i_ptr <<endl;

}

Calling program:

int m = 80;

print_int_42(m); cout << m<<endl<<endl;

set_int_42(&m); cout << m<<endl<<endl;

80

42

80

80

42

42

Xiaoyan Li, 2007Xiaoyan Li, 2007 4040

Array ParametersArray Parameters

Compare ordinary and Dynamic arraysCompare ordinary and Dynamic arraysCalling program:

int ages[30];

make_all_20(ages, 30);

void make_all_20(int data[ ], size_t size){ for (int i = 0 ; i< size; i++) {

data[i] = 20; }}

- An array parameter automatically treated as pointer to the first entry (– value or reference?)

- In the function prototype and implementation, size of the array is not specified inside bracket but by another parameter

Calling program:

int *ages;ages = new int[30]make_all_20(ages, 30);

Xiaoyan Li, 2007Xiaoyan Li, 2007 4141

Pointers or Array as const ParametersPointers or Array as const Parameters

to make sure they will not be changedto make sure they will not be changed

Calling program:int *ages, *i_ptr;double aver_age;ages = new int [ 30 ];...aver_age = average(ages, 30);i_ptr = &ages[12]; // i_ptr = (ages+12);if (is_20(i_ptr)) cout <<“Sudent No. 13 is 20!”<<endl;

Protoptyes:bool is_20(const int* i_ptr);double average(const int data[ ], size_t size);

Xiaoyan Li, 2007Xiaoyan Li, 2007 4242

Reference Parameters that are PointersReference Parameters that are Pointers

if we want to change the pointer to a new locationif we want to change the pointer to a new location

Calling program:int *ages;int jone = 20; // assume &jone is 904 nowages = &jone;cout << “address that ages points to is ”<< ages<<endl;allocate_int_array(ages, 30);cout << “address that ages points to is ”<< ages<<endl;

void allocate_int_arrary(int* i_ptr, size_t size){ i_ptr = new int[size];}

XX

Xiaoyan Li, 2007Xiaoyan Li, 2007 4343

Reference Parameters that are PointersReference Parameters that are Pointers

if we want to change the pointer to a new locationif we want to change the pointer to a new location

Calling program:int *ages;int jone = 20; // assume &jone is 904 nowages = &jone;cout << “address that ages points to is ”<< ages<<endl;allocate_int_array(ages, 30);cout << “address that ages points to is ”<< ages<<endl;

void allocate_int_arrary(int*& i_ptr, size_t size){ i_ptr = new int[size];}

VV

Xiaoyan Li, 2007Xiaoyan Li, 2007 4444

Reference Parameters that are PointersReference Parameters that are Pointers

if we want to change the pointer to a new locationif we want to change the pointer to a new location

Calling program:int *ages;int jone = 20; // assume &jone is 904 nowages = &jone; cout << “address that ages points to is ”<< ages<<endl;allocate_int_array(ages, 30);cout << “address that ages points to is ”<< ages<<endl;

typedef int* integer_ptr; void allocate_int_arrary(integer_ptr& i_ptr, size_t size){ i_ptr = new int[size];}

VV

Xiaoyan Li, 2007Xiaoyan Li, 2007 4545

Solution to Assignment 1Solution to Assignment 1

//Constructor //Constructor

statistician::statistician( )statistician::statistician( )

{{

count = 0; // empty sequencecount = 0; // empty sequence

total = 0; // initial value for totaltotal = 0; // initial value for total

// We don't know how to initialize tinyest // We don't know how to initialize tinyest

//and largest until we have a first number//and largest until we have a first number

}}

Xiaoyan Li, 2007Xiaoyan Li, 2007 4646

Solution to Assignment 1Solution to Assignment 1

// MODIFICATION MEMBER FUNCTIONS// MODIFICATION MEMBER FUNCTIONS

void statistician::next(double r)void statistician::next(double r) { count++;{ count++; total += r;total += r; if (count == 1 ) if (count == 1 ) { tinyest = largest = r;}{ tinyest = largest = r;} elseelse { if (r < tinyest) { if (r < tinyest) tinyest = r;tinyest = r; if (r > largest)if (r > largest) largest = r;largest = r; }} }}

Xiaoyan Li, 2007Xiaoyan Li, 2007 4747

Solution to Assignment 1Solution to Assignment 1

// MODIFICATION MEMBER FUNCTIONS// MODIFICATION MEMBER FUNCTIONS

void statistician::reset( )void statistician::reset( ) {{ if ( length() == 0) return; if ( length() == 0) return; count = 0; // empty sequencecount = 0; // empty sequence total = 0; // initial value for totaltotal = 0; // initial value for total // We don't know how to initialize tinyest and // We don't know how to initialize tinyest and

//largest until we have a first number //largest until we have a first number }}

Xiaoyan Li, 2007Xiaoyan Li, 2007 4848

Solution to Assignment 1Solution to Assignment 1

// CONSTANT MEMBER FUNCTIONS// CONSTANT MEMBER FUNCTIONS

int statistician::length( ) constint statistician::length( ) const {{ // can use inline function instead// can use inline function instead return count;return count; }}

Xiaoyan Li, 2007Xiaoyan Li, 2007 4949

Solution to Assignment 1Solution to Assignment 1

// CONSTANT MEMBER FUNCTIONS// CONSTANT MEMBER FUNCTIONS

double statistician::sum( ) constdouble statistician::sum( ) const {{ // can use inline function instead// can use inline function instead return total;return total; }}

Xiaoyan Li, 2007Xiaoyan Li, 2007 5050

Solution to Assignment 1Solution to Assignment 1

// CONSTANT MEMBER FUNCTIONS// CONSTANT MEMBER FUNCTIONS

double statistician::mean( ) constdouble statistician::mean( ) const {{ // precondition length()>0// precondition length()>0 assert(length( ) > 0);assert(length( ) > 0); return total / count;return total / count; }}

Xiaoyan Li, 2007Xiaoyan Li, 2007 5151

Solution to Assignment 1Solution to Assignment 1

// CONSTANT MEMBER FUNCTIONS// CONSTANT MEMBER FUNCTIONS

double statistician::minimum( ) constdouble statistician::minimum( ) const {{ // precondition length()>0// precondition length()>0 assert(length( ) > 0);assert(length( ) > 0); return tinyest;return tinyest;

}}

Xiaoyan Li, 2007Xiaoyan Li, 2007 5252

Solution to Assignment 1Solution to Assignment 1

// CONSTANT MEMBER FUNCTIONS// CONSTANT MEMBER FUNCTIONS

double statistician::maximum( ) constdouble statistician::maximum( ) const {{ // precondition length()>0// precondition length()>0 assert(length( ) > 0);assert(length( ) > 0); return largest;return largest; }}

Xiaoyan Li, 2007Xiaoyan Li, 2007 5353

Solution to Assignment 1Solution to Assignment 1 // FRIEND FUNCTIONS// FRIEND FUNCTIONS statistician operator +(const statistician& s1, const statistician& statistician operator +(const statistician& s1, const statistician&

s2)s2) { // Check special cases{ // Check special cases if (s1.length() == 0 ) if (s1.length() == 0 ) return s2;return s2; if (s2.length() == 0 ) if (s2.length() == 0 ) return s1;return s1; statistician s;statistician s; s.count = s1.count + s2.count;s.count = s1.count + s2.count; s.total = s1.total + s2.total;s.total = s1.total + s2.total; s.tinyest = (s1.tinyest <= s2.tinyest) ? s1.tinyest: s.tinyest = (s1.tinyest <= s2.tinyest) ? s1.tinyest:

s2.tinyest;s2.tinyest; s.largest = (s1.largest >= s2.largest) ? s1.largest: s.largest = (s1.largest >= s2.largest) ? s1.largest:

s2.largest;s2.largest; return s;return s; }}

Xiaoyan Li, 2007Xiaoyan Li, 2007 5454

Solution to Assignment 1Solution to Assignment 1 // FRIEND FUNCTIONS// FRIEND FUNCTIONS

statistician operator *(double scale, const statistician& s)statistician operator *(double scale, const statistician& s) { if (s.length() == 0) return s;{ if (s.length() == 0) return s; statistician sx;statistician sx; sx.count = s.count;sx.count = s.count; sx.total = s.total * scale;sx.total = s.total * scale; if (scale >= 0 )if (scale >= 0 ) { sx.largest = s.largest*scale;{ sx.largest = s.largest*scale; sx.tinyest = s.tinyest*scale;sx.tinyest = s.tinyest*scale; }} else{sx.largest = s.tinyest*scale;else{sx.largest = s.tinyest*scale; sx.tinyest = s.largest*scale;sx.tinyest = s.largest*scale; }} return sx;return sx; }}

Xiaoyan Li, 2007Xiaoyan Li, 2007 5555

Solution to Assignment 1Solution to Assignment 1// NON-MEMBER functions for the statistician class// NON-MEMBER functions for the statistician class bool operator ==(const statistician& s1, const statistician& s2)bool operator ==(const statistician& s1, const statistician& s2) { if (s1.length() == 0 && s2.length() == 0) { if (s1.length() == 0 && s2.length() == 0) return true;return true; if (s1.length() == 0 && s2.length() !=0)if (s1.length() == 0 && s2.length() !=0) return false;return false; if (s2.length() == 0 && s1.length() !=0)if (s2.length() == 0 && s1.length() !=0) return false;return false; return (s1.length() == s2.length()) &&return (s1.length() == s2.length()) && (s1.sum() == s2.sum ()) &&(s1.sum() == s2.sum ()) && (s1.minimum() == s2.minimum()) &&(s1.minimum() == s2.minimum()) && (s1.maximum() == s2.maximum()) ; (s1.maximum() == s2.maximum()) ; }}}}

Xiaoyan Li, 2007Xiaoyan Li, 2007 5656

Reading and Programming AssignmentsReading and Programming Assignments

Reading before the next lectureReading before the next lecture Chapter 4. Sections 4.3-4.4Chapter 4. Sections 4.3-4.4 Dynamic Classes and the Law of the Big ThreeDynamic Classes and the Law of the Big Three

Programming Assignment 2 (Reminder)Programming Assignment 2 (Reminder) Detailed guidelines online!Detailed guidelines online! Due Oct. 1 (Monday)Due Oct. 1 (Monday)