CMPE 180A Data Structures and Algorithms in C++ February 15 Class Meeting Department of Computer Engineering San Jose State University Spring 2018 Instructor:

Slides:



Advertisements
Similar presentations
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Advertisements

Pointers Typedef Pointer Arithmetic Pointers and Arrays.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Computer Science 1620 Loops.
Pointers. Topics Pointers Pointer Arithmetic Pointers and Arrays.
Computer Science 1620 Function Scope & Global Variables.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
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.
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.
Basic Elements of C++ Chapter 2.
February 11, 2005 More Pointers Dynamic Memory Allocation.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
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.
Dynamic memory allocation and Pointers Lecture 4.
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 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Pointers What is the data type of pointer variables?
Pointers and Dynamic Arrays
EGR 2261 Unit 11 Pointers and Dynamic Variables
Pointers and Dynamic Arrays
Chapter Topics The Basics of a C++ Program Data Types
Chapter 7 Pointers and C-Strings
EGR 2261 Unit 10 Two-dimensional Arrays
CMPE Data Structures and Algorithms in C++ September 14 Class Meeting
Motivation and Overview
CMPE Data Structures and Algorithms in C++ September 7 Class Meeting
CMPE Data Structures and Algorithms in C++ September 28 Class Meeting
Basic Elements of C++.
CMPE 135: Object-Oriented Analysis and Design October 17 Class Meeting
CMPE 135: Object-Oriented Analysis and Design October 17 Class Meeting
Pointers and Pointer-Based Strings
CSC113: Computer Programming (Theory = 03, Lab = 01)
CMPE Data Structures and Algorithms in C++ February 22 Class Meeting
Andy Wang Object Oriented Programming in C++ COP 3330
Basic Elements of C++ Chapter 2.
Dynamic Memory Allocation
Chapter 2 Elementary Programming
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers and Dynamic Variables
Pointers, Dynamic Data, and Reference Types
Chapter 12 Pointers and Memory Management
C++ Pointers and Strings
CS 144 Advanced C++ Programming February 7 Class Meeting
C++ Programming Lecture 17 Pointers – Part I
Pointers and Pointer-Based Strings
CS 144 Advanced C++ Programming February 5 Class Meeting
COP 3330 Object-oriented Programming in C++
CS 144 Advanced C++ Programming February 12 Class Meeting
Pointers and dynamic objects
CS 144 Advanced C++ Programming January 31 Class Meeting
CS 144 Advanced C++ Programming February 12 Class Meeting
CS 144 Advanced C++ Programming February 21 Class Meeting
ENERGY 211 / CME 211 Lecture 10 October 13, 2008.
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
CMPE 152: Compiler Design March 19 Class Meeting
Presentation transcript:

CMPE 180A Data Structures and Algorithms in C++ February 15 Class Meeting Department of Computer Engineering San Jose State University Spring 2018 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);  * Hide the car behind a door.  * @return the door that the car is hidden behind. Door hide_car();

Assignment #2: Sample Solution, cont’d /**  * @return the player's first door choice, which is either 1, 2, or 3.  */ Door make_first_choice();  * Open 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 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);

Assignment #2: Sample Solution, cont’d /**  * @return a random door 1, 2, or 3.  */ Door random_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);  * Choose door 1, 2, or 3 that is not:  * @param first_door the player's first door choice.  * @param opened_door the opened door.  * @return the remaining door. Door choose_remaining_door(Door first_door, Door opened_door);

Assignment #3: Sample Solution /**  * Compute a Hilbert matrix of size n and its inverse. Test the inverse.  * @param n the size.  */ void hilbert(const int size);  * Print a square matrix.  * @param n the size of the matrix.  * @param M the matrix. void print(const int n, const double M[][MAX_SIZE]);  * Compute Z = A*B.  * @param n the size of the matrices.  * @param A the first matrix factor.  * @param B the second matrix factor.  * @param Z their product. void multiply(const int n, const double A[][MAX_SIZE],               const double B[][MAX_SIZE], double Z[][MAX_SIZE]);

Pointers Pointers are an extremely powerful feature of C and C++ programs. You would not be a competent C or C++ programmer if you did 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;

Quiz

Break

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

Pointers and Arrays An array variable is actually a pointer variable. The array/pointer variable points to the first element of the array. int a[3]; a int a[3]; int *p; p = a; a p

Pointer Arithmetic int a[3]; int *p; p = a; a p The following expressions all access the third array element: a[2] p[2] *(p+2) *(a+2) What is *p+2 ?

Pointer Arithmetic, cont’d int a[3]; int *p; p = a; a p Use a pointer to iterate through an array. In the above example, p initially points to the first element of the array. Then p++ points to the second element. And next, p++ points to the third element.

Dynamic Arrays Up until now, whenever we declared an array, we explicitly gave its size. Example: But suppose we don’t know until run time how many elements we need. Example: At run time, your program reads in a count of names, and then the names. You want to create an array that can hold exactly that many names. You can use a dynamic array (instead of a vector). int a[10];

Dynamic Arrays, cont’d If the size of the array you want is in variable n whose value you don’t know until run time, use the new operator to create an array of size n. Use a pointer variable to point to the first element of the dynamic array. When you’re done with the array, use the special form of the delete operator to remove the array from memory: string *names = new string[n]; delete [] names; Demo

char* and char** Recall that C programs didn’t have C++ style strings, but instead had arrays of characters. The declaration is for a dynamic character array, a C-string. If you have a dynamic array of C-strings, you need a pointer to a pointer of characters: char *cstr; char **cstr_array;

chrono #include <iostream> #include <vector> TimeVector.cpp #include <iostream> #include <vector> #include <chrono> using namespace std; using namespace std::chrono; void initialize_vector(vector<int> v) { for (int i = 0; i < 10000000; i++) v.push_back(i); }

chrono, cont’d #include <iostream> #include <iomanip> #include <vector> #include <chrono> using namespace std; using namespace std::chrono; long time_vector_initialization(vector<int> v, int n); int main() {     vector<int> v;     for (long n = 10000; n <= 100000000; n *= 10)     {         long elapsed_time = time_vector_initialization(v, n);         cout << "Elapsed_time for " << setw(9) << n << " : "              << setw(4) << elapsed_time << " ms" << endl;     } } TimeVector.cpp

chrono, cont’d long time_vector_initialization(vector<int> v, int n) {     steady_clock::time_point start_time = steady_clock::now();     v.clear();     for (int i = 0; i < n; i++) v.push_back(i);     steady_clock::time_point end_time = steady_clock::now();     // Other options include: nanoseconds, microseconds     long elapsed_time =             duration_cast<milliseconds>(end_time - start_time).count();     return elapsed_time; } See http://en.cppreference.com/w/cpp/chrono

Assignment #4. Big Pi You will compute and print the first 1,000 decimal digits of pi. Algorithm: Nonic convergence at https://en.wikipedia.org/wiki/Borwein's_algorithm You will use the Multiple-Precision Integers and Rationals (MPIR) library. http://mpir.org/ The library is distributed as C source files. Use the library to create and work with numbers with arbitrarily long precision.

Assignment #4. Big Pi, cont’d You will learn how to download the source files, compile them, and configure, build, and install the MPIR library. Useful skills to have, because you will most likely need to use other libraries in the future. graphics libraries circuit simulation libraries numerical computing libraries etc.

Assignment #4. Big Pi, cont’d Building and installing the MPIR library is straightforward on Linux and Mac OS. Therefore, if you are on Windows, use VirtualBox to run Linux as a virtual machine. VirtualBox: https://www.virtualbox.org/wiki/VirtualBox Debian Linux: https://www.debian.org/ Ubuntu Linux: https://www.ubuntu.com/ Download and install a Linux disk image (.iso file) into VirtualBox.

Assignment #4. Big Pi, cont’d Please work together to help each other to build and install MPIR. Programs must be individual work, as usual. Extra credit: Compute one million digits of pi.