CS 144 Advanced C++ Programming February 12 Class Meeting

Slides:



Advertisements
Similar presentations
Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.
Advertisements

This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Computer Science 1620 Function Scope & Global Variables.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 ES 314 Advanced Programming Lec 3 Sept 8 Goals: complete discussion of pointers discuss 1-d array examples Selection sorting Insertion sorting 2-d arrays.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers.
1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
Functions Pass by Reference Alina Solovyova-Vincent Department of Computer Science & Engineering University of Nevada, Reno Fall 2005.
February 11, 2005 More Pointers Dynamic Memory Allocation.
Pointer Data Type and Pointer Variables. Objectives: Pointer Data Type and Pointer Variables Pointer Declaration Pointer Operators Initializing Pointer.
Chapter 9 Pointers and Dynamic Arrays (9.1). Pointers A variables which holds the memory address for a variable of a specific type. Call-by-Reference.
Review 1 List Data Structure List operations List Implementation Array Linked List.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 14: Pointers.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
Variables and memory addresses
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9 Pointers and Dynamic Arrays.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
CMPE Data Structures and Algorithms in C++ September 9 Class Meeting Department of Computer Engineering San Jose State University Fall 2016 Instructor:
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
EGR 2261 Unit 11 Pointers and Dynamic Variables
Pointers and Dynamic Arrays
CMPE Data Structures and Algorithms in C++ September 14 Class Meeting
Chapter 9: Pointers.
Learning Objectives Pointers Pointer in function call
CMPE 135: Object-Oriented Analysis and Design October 17 Class Meeting
Pointers and Pointer-Based Strings
CSC113: Computer Programming (Theory = 03, Lab = 01)
CMPE 180A Data Structures and Algorithms in C++ February 15 Class Meeting Department of Computer Engineering San Jose State University Spring 2018 Instructor:
Andy Wang Object Oriented Programming in C++ COP 3330
Pointer Data Type and Pointer Variables
Dynamic Memory Allocation
Pointer Basics Psst… over there.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 9: Pointers.
CMPE 180A Data Structures and Algorithms in C++ February 1 Class Meeting Department of Computer Engineering San Jose State University Spring 2018 Instructor:
Object Oriented Programming COP3330 / CGS5409
Chapter 9: Pointers.
Pointers, Dynamic Data, and Reference Types
Constant pointers and pointers to constants
Pointers & Functions.
Chapter 12 Pointers and Memory Management
CS150 Introduction to Computer Science 1
C++ Pointers and Strings
Pointers Pointers point to memory locations
CS 144 Advanced C++ Programming February 7 Class Meeting
CS150 Introduction to Computer Science 1
Pointers and Pointer-Based Strings
CS 144 Advanced C++ Programming February 5 Class Meeting
Dynamic Memory.
CS150 Introduction to Computer Science 1
CS 144 Advanced C++ Programming January 31 Class Meeting
Pointers & Functions.
Pointer Data Type and Pointer Variables
Pointer Basics Psst… over there.
CS 144 Advanced C++ Programming February 12 Class Meeting
CS 144 Advanced C++ Programming February 21 Class Meeting
Pointer Data Type and Pointer Variables
ENERGY 211 / CME 211 Lecture 10 October 13, 2008.
CMPE 152: Compiler Design April 18 – 30 Labs
CS 144 Advanced C++ Programming March 21 Class Meeting
Programming Fundamental
C++ Pointers and Strings
Pointers, Dynamic Data, and Reference Types
CS 144 Advanced C++ Programming April 30 Class Meeting
CS 144 Advanced C++ Programming April 30 Class Meeting
Presentation transcript:

CS 144 Advanced C++ Programming February 12 Class Meeting Department of Computer Engineering San Jose State University Spring 2019 Instructor: Ron Mak www.cs.sjsu.edu/~mak

Assignment #2: Sample Solution #include <cassert> using namespace std; typedef int Door; const int SIMULATION_COUNT = 100; /**  * Run a simulation.  * @param sequence the sequence number.  * @param win1 number of first choice wins.  * @param win2 number of second choice wins.  */ void simulate(int sequence, int& win1, int& win2);

Assignment #2: Sample Solution /**  * Hide the car behind a door.  * @return the door that the car is hidden behind.  */ Door hide_car();  * @return the player's first door choice, which is either 1, 2, or 3. Door make_first_choice();  * @return a random door 1, 2, or 3. Door random_door();

Assignment #2: Sample Solution, cont’d /**  * Monty opens a door that is not:  * @param first_choice_door the player's first door choice.  * @param car_behind_door the door that the car is hidden behind.  * @return the door to open.  */ Door open_door(Door first_choice_door, Door car_behind_door);  * Return a random door 1, 2, or 3 that is not:  * @param a_door a door.  * @param another_door another door, which can be equal to a_door.  * @return the random door. Door random_door_not(Door a_door, Door another_door);

Assignment #2: Sample Solution, cont’d /**  * Return the player's second door choice, which cannot be:  * @param first_door the player's first choice door.  * @param opened_door the opened door.  * @return the second door choice.  */ Door make_second_choice(Door first_door, Door opened_door);  * Choose door 1, 2, or 3 that is not:  * @param first_door the player's first door choice.  * @return the remaining door. Door choose_remaining_door(Door first_door, Door opened_door);

Assignment #2: Sample Solution, cont’d int main() {     int win1 = 0, win2 = 0;     cout << "   #     Car   First  Opened  Second    Win    Win" << endl;     cout << "        here  choice    door  choice  first second" << endl;     cout << endl;     srand(time(NULL));  // seed the random number generator     // Run the simulations.     for (int i = 1; i <= SIMULATION_COUNT; i++) simulate(i, win1, win2);     cout << setw(4) << win1 << " wins if stay with the first choice" << endl;     cout << setw(4) << win2 << " wins if switch to the second choice" << endl;     cout.setf(ios::fixed);     cout.setf(ios::showpoint);     cout.precision(1);     cout << "Win ratio of switch over stay: ";     cout << static_cast<double>(win2)/win1 << endl; }

Assignment #2: Sample Solution, cont’d void simulate(int sequence, int& win1, int& win2) {     // Perform a simulation.     Door car_behind_door    = hide_car();     Door first_choice_door  = make_first_choice();     Door opened_door        = open_door(first_choice_door,                                         car_behind_door);     Door second_choice_door = make_second_choice(first_choice_door,                                                  opened_door);     // Print the results.     cout << setw(4) << sequence << setw(8) << car_behind_door;     cout << setw(8) << first_choice_door << setw(8) << opened_door;     cout << setw(8) << second_choice_door;     if (first_choice_door == car_behind_door)     {         cout << "    yes";  // the car was behind the first door choice         win1++;     }     else         cout << "           yes";  // it was behind the second door choice         win2++;     cout << endl; }

Assignment #2: Sample Solution, cont’d Door hide_car() {     // The simulation randomly chooses the door to hide the car.     return random_door(); } Door make_first_choice()     // The simulation randomly makes the player's first door choice. Door random_door()     return rand()%3 + 1;

Assignment #2: Sample Solution, cont’d Door open_door(Door first_choice_door, Door car_behind_door) {     // Monty Hall knows which door the car is behind     // and so he opens a door that has a goat behind it.     Door opened_door = random_door_not(first_choice_door, car_behind_door);     assert(   (opened_door != first_choice_door)            && (opened_door != car_behind_door));     return opened_door; } Door random_door_not(Door a_door, Door another_door)     Door door;     // If doors a_door and another_door are the same, then randomly     // choose between the other two doors to return.     // Otherwise, return the third door.     do {         door = random_door();     } while ((door == a_door) || (door == another_door));     return door;

Assignment #2: Sample Solution, cont’d Door make_second_choice(Door first_door, Door opened_door) {     // The player's second door choice can't be     // the first door choice or the opened door.     Door second_choice = choose_remaining_door(first_door, opened_door);     assert(   (second_choice != first_door)            && (second_choice != opened_door));     return second_choice; } Door choose_remaining_door(Door first_door, Door opened_door)     // Check door 1 and door 2.     for (Door door = 1; door <= 2; door++)     {         if ((door != first_door) && (door != opened_door)) return door;     }     return 3;  // if not door 1 or door 2

Pointers Pointers are an extremely powerful feature of C and C++ programs. You cannot be a competent C or C++ programmer if you do not know how to use pointers effectively. Pointers can also be extremely dangerous. Many runtime errors and program crashes are due to misbehaving pointers. Pointers are a prime cause of memory errors.

An int vs. Pointer to an int A graphical representation of an int variable named num and its value: A graphical representation of a pointer variable named ptr that points to an int value of a variable named num: 5 num 5 ptr num

Declaring and Assigning Pointers After the following statements are executed: We have this situation: int num = 5; int *ptr = &num; 5 ptr num

Pointers are Addresses To declare that a variable is a pointer, use a * before the variable name: ptr can point to an int value ptr2 can point to a double value The statement assigns the address of variable num to pointer variable ptr Make ptr point to the address of variable num. int *ptr; double *ptr2; & is the address-of operator ptr = &num;

The Dereferencing Operator 5 ptr num int num = 5; int *ptr = &num; To get the value that pointer ptr is pointing to: Now the * is the dereferencing operator. “Follow the pointer to get what it’s pointing to.” We can use *ptr in an expression. Example: *ptr + 2 gives the value 7. *ptr

The Dereferencing Operator, cont’d 5 ptr num int num = 5; int *ptr = &num; In the above example, both *ptr and num refer to the same value 5. What happens if we execute the statement? Now both num and *ptr are 9. *ptr = 9; 9 ptr num

A Pointer Declaration Warning You can declare several pointer variables in one line: How many pointer variables do we have? Only ptr1 is a pointer to a double value. ptr2 and ptr3 are simple double variables. double *ptr1, *ptr2, *ptr3; double* ptr1, ptr2, ptr3;

The new Operator So far, all our variables have names and are created automatically when we declare them: We can also create nameless variables. The new operator returns a pointer to the variable it just created. This is ideal for pointer variables. int num; int *ptr = new int(42); 42 ptr a nameless variable

The delete Operator If your program creates nameless variables, then it must remove them from memory when the program no longer needs them. Delete from memory the nameless variable that ptr points to. If your program doesn’t get rid of all the nameless variables it created, those variables clutter up memory, and therefore you are said to have a memory leak. delete ptr;

Pointer Parameters We can pass a pointer by value to a function: We can change the value of the variable that ptr1 points to. We can also pass a pointer by reference: We can change what variable ptr1 points to. Ugly syntax! void foo(int *ptr1, double *ptr2); void bar(int* &ptr1, double* &ptr2);

typedef Use typedefs to simplify pointer notation: Now you can use IntPtr in place of int * and DoublePtr in place of double * typedef int *IntPtr; typedef double *DoublePtr; void foo(IntPtr ptr1, DoublePtr ptr2); void bar(IntPtr& ptr1, DoublePtr& ptr2);

Using Pointers to Pass-by-Reference C programmers used pointers to pass parameters by reference. Example: A call to the function needed the address of the corresponding argument: Because parm points back to the actual argument, the function can use *parm to change the value of the actual argument. function baz(int *parm); int arg; baz(&arg);

Assignment #3. War and Peace This assignment uses strings and vectors. Review last week’s practice problems. Write a program to read the text of the long Russian novel War and Peace. Search for several names of characters: Makar Alexeevich Joseph Bazdeev Boris Drubetskoy Tricky: A name can be split across two consecutive lines.

Assignment #3. War and Peace, cont’d Learn to use the online C++ reference: For vectors: http://www.cplusplus.com/reference/vector/vector/ For strings: http://www.cplusplus.com/reference/string/string/ Use vector and string functions. Do not use arrays or C-strings.