CMSC202 Computer Science II for Majors

Similar documents
CMSC 341 Lecture 2 Dynamic Memory and Pointers

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Object oriented programming C++

Exam 3 Chapters 7 & 9

Binghamton University. CS-211 Fall Pointers

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Homework #3 CS2255 Fall 2012

a data type is Types

C++ for Java Programmers

Pointers, Arrays and Parameters

What is an algorithm?

Sixth lecture; classes, objects, reference operator.

Pointers, Dynamic Data, and Reference Types

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 6: Pointers

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Slides adopted from T. Ferguson Spring 2016

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

Pointers in C/C++ 1 Memory Addresses 2

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Reference operator (&)

Dynamic Memory Allocation

Chapter 9: Pointers. Copyright 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved.

Procedural Programming

Chapter 9: Getting the Address of a Variable. Something Like Pointers: Arrays. Pointer Variables 8/23/2014. Getting the Address of a Variable

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #33 Pointer Arithmetic

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

FORM 2 (Please put your name and form # on the scantron!!!!)

CSCI 104 Memory Allocation. Mark Redekopp David Kempe

CMSC202 Computer Science II for Majors

CS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018

Intro to C: Pointers and Arrays

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

BITG 1113: Function (Part 2) LECTURE 5

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

C Pointers. 6th April 2017 Giulio Picierro

Pointers. Lecture 1 Sections Robb T. Koether. Hampden-Sydney College. Wed, Jan 14, 2015

Computer Programming Lecture 12 Pointers

Binghamton University. CS-211 Fall Pointers

CS107, Lecture 6 More Pointers and Arrays

C Pointers 2013 Author Riko H i

Tutorial 10 Pointers in C. Shuyue Hu

Week 7: Pointers and Arrays. BJ Furman 02OCT2009

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Pointers and Strings Prentice Hall, Inc. All rights reserved.

Lectures 6/7 Pointers and Dynamic Arrays

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Pointers Pointer Variables. Pointer Variables Getting the Address of a Variable. Each variable in program is stored at a

9.2 Pointer Variables. Pointer Variables CS Pointer Variables. Pointer Variables. 9.1 Getting the Address of a. Variable

These are notes for the third lecture; if statements and loops.

CS107, Lecture 9 C Generics Function Pointers

CMSC 202 Midterm Exam 1 Fall 2015

CMSC 341 Lecture 10 Binary Search Trees

CIS 190: C/C++ Programming. Lecture 2 Pointers and More

CS162 - POINTERS. Lecture: Pointers and Dynamic Memory

Principles of Programming Pointers, Dynamic Memory Allocation, Character Arrays, and Buffer Overruns

内存管理. Memory management

Arrays in C++ Instructor: Andy Abreu

EL2310 Scientific Programming

Exercise: Inventing Language

Pointers! Arizona State University 1

Pointers. Memory. void foo() { }//return

CprE 288 Introduction to Embedded Systems Exam 1 Review. 1

(7-1) Modular Programming H&K Chapter 6. Instructor - Andrew S. O Fallon CptS 121 (February 21, 2018) Washington State University

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

Fundamentals of Programming Session 19

Numerical Computing in C and C++ Jamie Griffin. Semester A 2017 Lecture 2

Processor. Lecture #2 Number Rep & Intro to C classic components of all computers Control Datapath Memory Input Output

Review: C Strings. A string in C is just an array of characters. Lecture #4 C Strings, Arrays, & Malloc

12. Pointers Address-of operator (&)

Pointers and Strings. Adhi Harmoko S, M.Komp

Chapter 9. Pointers and Dynamic Arrays

REFERENCES, POINTERS AND STRUCTS

Outline. Introduction. Pointer variables. Pointer operators. Calling functions by reference. Using const with pointers. Examples.

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS ) Pointers. Chapter No 7

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Pointers. Reference operator (&) ted = &andy;

CS 61c: Great Ideas in Computer Architecture

CS2351 Data Structures. Lecture 7: A Brief Review of Pointers in C

Variation of Pointers

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

Week 3: Pointers (Part 2)

Object-Oriented Programming

EECS 183, Week 5. General. Variables I/O. 0. At which location do you have to take the exam? 1. Source code vs. object code? 2. What s a library?

CS2255 HOMEWORK #1 Fall 2012

Programming in C. Pointers and Arrays

Linked Lists CS 16: Solving Problems with Computers I Lecture #16

Pointers and scanf() Steven R. Bagley

CSCI 262 Data Structures. Arrays and Pointers. Arrays. Arrays and Pointers 2/6/2018 POINTER ARITHMETIC

pointers + memory double x; string a; int x; main overhead int y; main overhead

Transcription:

CMSC202 Computer Science II for Majors Lecture 04 Pointers Dr. Katherine Gibson Based on slides by Chris Marron at UMBC

Last Class We Covered C++ Functions Parts of a function: Prototype Definition Call Arrays Declaration Initialization Passing arrays to function 2

Any Questions from Last Time?

Note Taker Still Needed A peer note taker is still needed for this class. A peer note taker is a volunteer student who provides a copy of his or her notes for each class session to another member of the class who has been deemed eligible for this service based on a disability. Peer note takers will be paid a $200 stipend for their service. Peer note taking is not a part time job but rather a volunteer service for which enrolled students can earn a stipend for sharing the notes they are already taking for themselves. If you are interested in serving in this important role, please fill out a note taker application on the Student Support Services website or in person in the SSS office in Math/Psychology 213. 4

Today s Objectives To review functions and how they work To begin to understand pointers Pointers are a complicated and complex concept You may not immediately get it that s fine! To learn how pointers can be used in functions Passing in entire arrays Returning more than one value 5

Functions and Arguments

Review of Functions Here is a simple function that adds one to an integer and returns the new value 7 Definition: int AddOne (int num) { } return num++; Call: int enrolled = 99; enrolled = AddOne(enrolled);

Function Arguments What is happening behind the scenes? When the AddOne() function is called, the value of the variable is passed in as an argument The value is saved in AddOne s local variable num Changes made to x do not affect anything outside of the function AddOne() This is called the scope of the variable 8

Scope Scope is the visibility of variables Which parts of your program can see a variable Every function has its own scope: The main() function has a set of variables So does the AddOne() function They can t see each other s variables Which is why we must pass arguments and return values between functions 9

Addresses Every variable in a program is stored somewhere in the computer s memory This location is called the address All variables have a unique address Addresses are normally expressed in hex: 0xFF00 0x70BF 0x659B 10

Array Addresses An array also has an address The location of the first element of the array char terry[6] = "hello"; We ll discuss arrays more later today 11

Function Scope What happens when AddOne() is called? int age = 20; age = AddOne(age); The value of age is passed in, and stored in another variable called num What is the scope of each of these variables? age is in the scope of main() num is in the scope of AddOne() 12

Function Calls The blue box represents scope The house shape is a variable s name, address, and value main() age 0x1000 20 13

Function Calls When main() calls AddOne() The value is passed in, and stored in num main() AddOne() age 0x1000 20 num 0x5286 20 14

Function Calls When the AddOne() function changes num, what happens to the age variable? Nothing! main() AddOne() age 0x1000 20 num 0x5286 20 21 15

Function Calls How do we update the value of age? By returning the new value and assigning it to age main() AddOne() age 0x1000 20 21 num 0x5286 21 16

Function Calls What happens when the function returns? The function is over AddOne() and num are out of scope main() age 0x1000 21 AddOne() And are num no longer available 0x5286 to us! 21 17

Pointer Introduction

Pointers A pointer is a variable whose value is an address to somewhere in memory cout << "x is " << x << endl; cout << "ptr is " << ptr << endl; This will print out something like: x is 37 ptr is 0x7ffedcaba5c4 19

Pointers Pointers are incredibly useful to programmers! Allow functions to Modify multiple arguments Use and modify arrays as arguments Programs can be made more efficient Dynamic objects can be used We ll discuss this later in the semester 20

Creating Pointers A pointer is just like any regular variable It must have a type It must have a name It must contain a value To tell the compiler we re creating a pointer, we need to use * in the declaration int *myptr; 21

Pointer Declarations All of the following are valid declarations: int *myptr; int* myptr; int * myptr; Even this is valid (but don t do this): int*myptr; this is the most common way The spacing and location of the star ( * ) don t matter to the compiler 22

Pointer Declarations Since position doesn t matter, why use this? int *myptr; What does this code do? int *myptr, yourptr, ourptr; It creates one pointer and two integers! What does this code do? int *myptr, *yourptr, *ourptr; 23 It creates three integers!

Pointers and Regular Variables As we said earlier, pointers are just variables Instead of storing an int or a float or a char, they store an address in memory num 0x5286 address ptr 0x560B address (where it lives in memory) 20 value regular variable 0xFF8A pointer variable value (where it points in memory) 24

Assigning Value to a Pointer The value of a pointer is always an??? address To get the address of any variable, we use an ampersand ( & ) int x = 5; int *xptr; // xptr "points to" x xptr = &x; 25

Assigning to a Pointer All of these are valid assignments: int x = 5; int *ptr1 = &x; int *ptr2; ptr2 = &x; int *ptr3 = ptr1; 26

Assigning to a Pointer This is not a valid assignment why? int x = 5; char *ptr4 = &x; Pointer type must match the type of the variable whose address it stores Compiler will give you an error: cannot convert int* to char* in initialization 27

Making Pointers Point When we assign a value to a pointer, we are telling it where in memory to point to // create both variables double val; double *ptr; // assign values val = 5.6; ptr = &val; val 0xBB08 5.6 garbage ptr 0x564F 28 0xBB08 garbage

The Asterisk and the Ampersand

Review: The Ampersand The ampersand Returns the address of a variable Must be placed in front of the variable name int x = 5; int *varptr = &x; int y = 7; varptr = &y; 30

The Asterisk (or Star ) The star symbol ( * ) has two purposes when working with pointers The first purpose is to tell the compiler that the variable will store an address In other words, declaring a pointer int *varptr = &x; void fxnname (float *fltptr); 31

The Asterisk (or Star ) The second purpose is to dereference a pointer Dereferencing a pointer means the compiler Looks at the address stored in the pointer Goes to that address in memory Looks at the value stored at that address ptr val address 0x564F 0xBB08 address value 0xBB08 5.6 value 32

Dereferencing What we do at that point depends on why the pointer is being dereferenced A dereference can be in three places On the left hand side of the assignment operator On the right hand side of the assignment operator In an expression without an assignment operator For example, a print statement 33

Dereferencing Examples int val = *ptr; on the right hand side of the assignment operator Look at the value, but don t change it ptr val address 0x564F 0xBB08 address value 0xBB08 17 value 34

Dereferencing Examples *ptr = 36; on the left hand side of the assignment operator Access the variable and change its value ptr val address 0x564F 0xBB08 address value 0xBB08 17 36 value 35

Dereferencing Examples cout << "Value stored is " << *ptr; in an expression without an assignment operator Look at the value, but don t change it ptr val address 0x564F 0xBB08 address value 0xBB08 36 value 36

AddTwo()

The AddTwo() Function Let s create a new function that adds 2 to two integers So 22 and 98 will become 24 and 100 Can we do this with a regular function? (That is, without using pointers?) No! Functions can only return one value! We must use pointers to change more than one value in a single function 38

The AddTwo() Function We want our function to look something like this pseudocode: // take in two ints, return nothing void AddTwo( <two integers> ) { } // add two to the first int // add two to the second int // keep the values -- but how? 39

Passing Pointers to a Function To tell the compiler we are passing an address to a function, we will use int *varptr void AddTwo (int *ptr1, int *ptr2) Just like int num tells the compiler that we are passing in an integer value int AddOne (int num) 40

Writing AddTwo() Given that AddOne() looks like this: int AddOne (int num) { } return num++; How do we write the AddTwo function? void AddTwo (int *ptr1, int *ptr2) { 41 }

AddTwo() void AddTwo (int *ptr1, int *ptr2) { /* add two to the value of the integer ptr1 points to */ *ptr1 = *ptr1 + 2; /* add two to the value of the integer ptr2 points to */ *ptr2 = *ptr2 + 2; /* return nothing */ } 42

Calling AddTwo() Now that the function is defined, let s call it It takes in the address of two integers Pass it two int pointers: AddTwo(numPtr1, numptr2); Pass it the addresses of two ints: AddTwo(&num1, &num2); Pass it a combination: AddTwo(numPtr1, &num2); 43

Literals and Pointers What about the following does it work? AddTwo(&15, &3); No! 15 and 3 are literals, not variables They are not stored in memory They have no address (They re homeless!) 44

Announcements The course policy agreement is due today Project 1 has been released Found on Professor s Marron website Due by 9:00 PM on February 23rd Get started on it now! Next time: References And a review of pointers 45