Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Xiaoyan Li, 2007 1 CSC211 Data Structures Lectures 6/7 Pointers and Dynamic Arrays Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke."— Presentation transcript:

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

2 Xiaoyan Li, About Quiz 2 from Lecture 5 bool bag::erase_one(const int& target) {if (count(target) = = 0) return false; else { else { for (int i=0; i

3 Xiaoyan Li, Review: (Lecture 5) p Bag class definition/implementation details p Inline functions p constructor, size p Other basic functions p insert, erase_one, erase, count p More advanced functions p operators +, +=, - p Time Analysis p Big-O p Introduction to sequence

4 Xiaoyan Li, 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 (, ending location>, );

5 Xiaoyan Li, 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 ?

6 Xiaoyan Li, 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 constructor size_t size2 = b2.size(); // use member function size for (index = 0; index < size2; ++index) { int target = b2.data[index]; // use private member variable if (answer.count(target) ) // use function count answer.erase_one(target); // use function erase_one } return answer; }

7 Xiaoyan Li, Why Friend functions? p A friend function can access all private member variables of a class. p A special feature in C++ (not supported in java or C#)

8 Xiaoyan Li, Advantages of Friend functions? p Provide a degree of freedom in the interface design options p Choose between member functions (x.f()) and friend functions (f(x)) p Having a public get() and set() member function for a private datum is OK only when the private datum "makes sense" from outside the class. In many cases, they are almost as bad as public data: they hide (only) the name of the private datum, but they don't hide the existence of the private datum. p Should my class declare a member function or a friend function?

9 Xiaoyan Li, Advantages of Friend functions? p Provide a degree of freedom in the interface design options p Choose between member functions (x.f()) and friend functions (f(x)) p Having a public get() and set() member function for a private datum is OK only when the private datum "makes sense" from outside the class. In many cases, they are almost as bad as public data: they hide (only) the name of the private datum, but they don't hide the existence of the private datum. p Should my class declare a member function or a friend function? p Use a member when you can, and a friend when you have to. (Use it wisely! Do not make too many friends )

10 Xiaoyan Li, Why Pointers and Dynamic Memory p Limitation of our bag class p class bag { public: static const size_t CAPACITY = 20;... private: int data[CAPACITY]; size_t used; };

11 Xiaoyan Li, Why Pointers and Dynamic Memory p Limitation of our bag class p bag::CAPACITY constant determines the capacity of every bag p wasteful (if too big) and hard to reuse (if too small) p need to change source code and recompile p Solution: p provide control over size in running time p <= dynamic arrays p <= pointers and dynamic memory

12 Xiaoyan Li, Outline (Reading Ch 4.1 – 4.2) p Pointers p *(asterisk) and &(ampersand) operators  Dynamic Variables and new Operator p Dynamic Arrays and Dynamic Objects p Stack (local) vs. heap (dynamic) memory  Garbage Collection and delete Operator p Parameters revisited p Pointers and Arrays as Parameters

13 Xiaoyan Li, Pointer Variable p First let’s have a look at local variables p Q: What’s the value of i? ? … int i;i By this declaration, a cell of 4 adjacent bytes (in some machines) are allocated in the local memory (called stack memory) Address 9## is just for illustration. Real address may have 64 bits

14 Xiaoyan Li, Pointer Variable p First let’s have a look at local variables p Q: How to get the address? p Q: What is the binary representation of 42? … int i; i = 42;i The assignment put number 42 in the cell. The memory address of the 1 st byte is the address of the variable i – the pointer to i

15 Xiaoyan Li, Pointer Variable p First let’s have a look at local variables p Q: Where can we store &i? … int i; i = 42; cout << &i;i & (ampersand) operator - “address of ” operator - &i is 900 ! -Note: two meanings of &

16 Xiaoyan Li, Pointer Variable p The memory address can be stored a special pointer variable p Q: How to point i_ptr to i? 42 ? … int i=42; int *i_ptr;ii_ptr 1. the type of the data that the pointer points to: int 2. an asterisk (*) 3. the name of the newly declared pointer: i_ptr

17 Xiaoyan Li, Pointer Variable p Assign the address of i to i_ptr 42 ? … int i=42; int *i_ptr; i_ptr = &i;ii_ptr What are the results of -cout << i; -cout << i_ptr; -cout << &i_ptr;

18 Xiaoyan Li, Pointer Variable p The i_ptr holds the address of an integer, not the integer itself … int i=42; int *i_ptr; i_ptr = &i;ii_ptr Two ways to refer to i -cout << i; -cout << *i_ptr; - dereferencing operator * - dereferencing operator * - two meanings of * - two meanings of *

19 Xiaoyan Li, Operators * and & p Operator * p Pointer declaration int *i_ptr; p dereferencing operator cout << *i_ptr; p Two different meanings! p Operator & p Reference parameter void funct(int& i); void funct(int& i); p “address of ” operator i_ptr = &i;

20 Xiaoyan Li, Syntax and Naming Issues p How to declare two pointers in a line char *c1_ptr, *c2_ptr; p instead of char* c1_ptr, c2_ptr;  For clarity, use _ptr or cursor for pointer variables

21 Xiaoyan Li, Assignment Operators with Pointers p p2 = p1 int i = 42; int *p1, *p2; p1 = &i; p2 = p1; 42i 900 address value name ?p1904?p2908 Both p1 and p2 point to the same integer 900p p ? ? … ip1 p

22 Xiaoyan Li, Assignment Operators with Pointers p *p2 = *p1 int i = 42; int *p1, *p2; p1 = &i; *p2 = *p1; 42i 900 address value name ?p1904?p2908 p2 doesn’t point to anywhere, so assigning value to *p2 will cause a running time error! 900p ? ? … ip1 p2 900 X

23 Xiaoyan Li, ?p p1908 ?p p2912 Assignment Operators with Pointers p *p2 = *p1 int i = 42; int j = 20; int *p1, *p2; p1 = &i; p2 = &j; *p2 = *p1;42i900 Both i (*p1) and j (*p2) will have the same integer values ? ? … ij p1 p j904 42j904 42

24 Xiaoyan Li, Outline (Reading Ch 4.1 – 4.2) p Pointers p *(asterisk) and &(ampersand) operators  Dynamic Variables and new Operator p Dynamic Arrays and Dynamic Objects p Stack (local) vs. heap (dynamic) memory  Garbage Collection and delete Operator p Parameters revisited p Pointers and Arrays as Parameters

25 Xiaoyan Li, Dynamic Variables p We cannot use a pointer if not initialized p need to point to a declared variable p How to use a pointer without connecting with a declared ordinary variable? p Solution: Dynamic (allocated) variables p not declared, therefore no identifier p created during execution p Real power of pointers is with dynamic variables

26 Xiaoyan Li, The new Operator p allocates memory and return a pointer ?p1900 int *p1; p1 = new int; *p1 = 20;?? p1 points to a dynamic integer variable without any identifier (name) - p1 points to a dynamic integer variable without any identifier (name) - dynamic memory comes from the programs’ heap (free store) 20?10500 ? … … p1?

27 Xiaoyan Li, Dynamic Arrays p new can allocate an entire array all at once ?p1900 int *p1; p1 = new int[4]; p1[2] = 20; cout<<*(p1+2); 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 - two ways to access p1 (array or pointer) ? … … p1?

28 Xiaoyan Li, Accessing Dynamic Array p Use array notation p the 1 st entry p1[0] = 18; p the 3 rd entry p1[2] = 20; p1[2] = 20; p the ith entry p1[i-1] = 19; p Use pointer notation p the 1 st entry *p1 = 18; p the 3 rd entry *(p1+2) = 20; *(p1+2) = 20; p the ith entry *(p1+i-1) = 19;

29 Xiaoyan Li, Dynamic Array Example: (2 minutes) p A program read ages of each of MHC classes, with varying sizes, calculate the average, and then print out the average. – think about the variables needed. size_t size; int *ages; float average; cin >> size; ages = new int[size]; // input ages of all students // calculate average // print average …

30 Xiaoyan Li, Dynamic Objects of a class p new can also allocate a dynamic object ?p1900 point *p1; p1 = new point(1.0, 2.0); cout<< (*p1).get_x(); cout get_x(); - p1 points to dynamic object without name - p1 points to dynamic object without name - parameters can be used as in declaration - two ways to access p1 (* and ->) ? … … p1?

31 Xiaoyan Li, Array of Dynamic Objects of a class Q: Are the followings correct? point3 demo Q: Are the followings correct? point3 demopoint3 demopoint3 demo p Ten points with default coordinates? p1 = new point[10]; p1 = new point[10]; p Ten points with the same coordinates? p1 = new point(1.0, 2.0)[10]; p1 = new point(1.0, 2.0)[10]; p 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 function void point::set(double x_init, double y_init); VXV

32 Xiaoyan Li, Programming Assignment 2 p Detailed guidelines online! p In addition to your source files, also send in running results of the “exam” programs, Cut & paste in a text file p The prototypes and pre/postconditions of functions in header files should not be changed. p Due Oct. 1 (Monday)

33 Xiaoyan Li, Review: Pointers from Lecture 6 p What is a pointer? p How to declare a pointer variable? p How to declare more pointers in one line? p Operators & and * (two ways to refer to a variable) p Dynamic variables, dynamic objects, dynamic arrays? (two ways to refer to array elements.) p What is the function of operator “new”?

34 Xiaoyan Li, Failure of the new Operator p Dynamic memory via new operator comes from heap of a program ( p Dynamic memory via new operator comes from heap of a program (i_ptr = new int; d_ptr = new double[20]; ) p_ptr = new point(1.0, 2.0);) p Heap size from several K to 1GB, however fixed  Could run out of room therefore cause a bad_alloc exception p error message and program halts p Good practice 1: document which functions use new  Good practice 2: garbage collection by delete operator

35 Xiaoyan Li, Outline (Reading Ch 4.1 – 4.2) p Pointers p *(asterisk) and &(ampersand) operators  Dynamic Variables and new Operator p Dynamic Arrays and Dynamic Objects p Stack (local) vs. heap (dynamic) memory  Garbage Collection and delete Operator p Parameters revisited p Pointers and Arrays as Parameters

36 Xiaoyan Li, The delete Operator p Release any dynamic memory (heap memory) 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. 1.delete resets these pointers 2. 2.delete removes dynamic objects pointed by the pointers 3. 3.nothing happens to the pointers themselves XVV

37 Xiaoyan Li, Outline (Reading Ch 4.1 – 4.2) (Next Lecture) p Pointers p *(asterisk) and &(ampersand) operators  Dynamic Variables and new Operator p Dynamic Arrays and Dynamic Objects p Stack (local) vs. heap (dynamic) memory  Garbage Collection and delete Operator p Parameters revisited p Pointers and Arrays as Parameters

38 Xiaoyan Li, Pointers and Arrays as Parameters p Value parameters that are pointers p Array parameters p Pointers and arrays as const parameters p Reference parameters that are pointers

39 Xiaoyan Li, Value parameters that are pointers p Compare ordinary and pointer variables void print_int_42(int i) { cout << i<

40 Xiaoyan Li, Array Parameters p Compare ordinary and Dynamic arrays Calling 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);

41 Xiaoyan Li, Pointers or Array as const Parameters p to 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!”<

42 Xiaoyan Li, Reference Parameters that are Pointers p if we want to change the pointer to a new location Calling program: int *ages; int jone = 20; // assume &jone is 904 now ages = &jone; cout << “address that ages points to is ”<< ages<

43 Xiaoyan Li, Reference Parameters that are Pointers p if we want to change the pointer to a new location Calling program: int *ages; int jone = 20; // assume &jone is 904 now ages = &jone; cout << “address that ages points to is ”<< ages<

44 Xiaoyan Li, Reference Parameters that are Pointers p if we want to change the pointer to a new location Calling program: int *ages; int jone = 20; // assume &jone is 904 now ages = &jone; cout << “address that ages points to is ”<< ages<

45 Xiaoyan Li, Solution to Assignment 1 //Constructor statistician::statistician( ) { count = 0; // empty sequence count = 0; // empty sequence total = 0; // initial value for total total = 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}

46 Xiaoyan Li, Solution to Assignment 1 // MODIFICATION MEMBER FUNCTIONS // MODIFICATION MEMBER FUNCTIONS void statistician::next(double r) { count++; { count++; total += r; total += r; if (count == 1 ) if (count == 1 ) { tinyest = largest = r;} { tinyest = largest = r;} else else { if (r < tinyest) { if (r < tinyest) tinyest = r; tinyest = r; if (r > largest) if (r > largest) largest = r; largest = r; } }

47 Xiaoyan Li, Solution 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 sequence count = 0; // empty sequence total = 0; // initial value for total total = 0; // initial value for total // We don't know how to initialize tinyest and //largest until we have a first number // We don't know how to initialize tinyest and //largest until we have a first number }

48 Xiaoyan Li, Solution to Assignment 1 // CONSTANT MEMBER FUNCTIONS int statistician::length( ) const { // can use inline function instead // can use inline function instead return count; return count; }

49 Xiaoyan Li, Solution to Assignment 1 // CONSTANT MEMBER FUNCTIONS // CONSTANT MEMBER FUNCTIONS double statistician::sum( ) const double statistician::sum( ) const { // can use inline function instead // can use inline function instead return total; return total; }

50 Xiaoyan Li, Solution to Assignment 1 // CONSTANT MEMBER FUNCTIONS double statistician::mean( ) const double statistician::mean( ) const { // precondition length()>0 // precondition length()>0 assert(length( ) > 0); assert(length( ) > 0); return total / count; return total / count; }

51 Xiaoyan Li, Solution to Assignment 1 // CONSTANT MEMBER FUNCTIONS double statistician::minimum( ) const double statistician::minimum( ) const { // precondition length()>0 // precondition length()>0 assert(length( ) > 0); assert(length( ) > 0); return tinyest; return tinyest; }

52 Xiaoyan Li, Solution to Assignment 1 // CONSTANT MEMBER FUNCTIONS double statistician::maximum( ) const double statistician::maximum( ) const { // precondition length()>0 // precondition length()>0 assert(length( ) > 0); assert(length( ) > 0); return largest; return largest; }

53 Xiaoyan Li, Solution to Assignment 1 // FRIEND FUNCTIONS // FRIEND FUNCTIONS statistician operator +(const statistician& s1, const statistician& s2) statistician operator +(const statistician& s1, const statistician& 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: s2.tinyest; s.tinyest = (s1.tinyest <= s2.tinyest) ? s1.tinyest: s2.tinyest; s.largest = (s1.largest >= s2.largest) ? s1.largest: s2.largest; s.largest = (s1.largest >= s2.largest) ? s1.largest: s2.largest; return s; return s; }

54 Xiaoyan Li, Solution 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; }

55 Xiaoyan Li, Solution to Assignment 1 // 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()) ; }}

56 Xiaoyan Li, Reading and Programming Assignments p Reading before the next lecture p Chapter 4. Sections p Dynamic Classes and the Law of the Big Three p Programming Assignment 2 (Reminder) p Detailed guidelines online! p Due Oct. 1 (Monday)


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

Similar presentations


Ads by Google