Today USING POINTERS. Functions: parameters and arguments. Todaywewilllookattopicsrelatingtotheuseofpointers

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

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

BEng (Hons) Electronic Engineering. Resit Examinations for / Semester 1

Pointers II. Class 31

Pointer Data Type and Pointer Variables

Fundamentals of Programming. Lecture 19 Hamed Rasifard

Memory and Pointers written by Cathy Saxton

Homework #3 CS2255 Fall 2012

Constants, References

Implementing an ADT with a Class

C++ Programming for Non-C Programmers. Supplement

CSC 211 Intermediate Programming. Pointers

CS24 Week 3 Lecture 1

Come and join us at WebLyceum

Exercise 1.1 Hello world

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

1. In C++, reserved words are the same as predefined identifiers. a. True

Agenda / Learning Objectives: 1. Map out a plan to study for mid-term Review the C++ operators up to logical operators. 3. Read about the tips

CS111: PROGRAMMING LANGUAGE II

C++ For Science and Engineering Lecture 12

Pointers. Developed By Ms. K.M.Sanghavi

C++ Programming for Non-C Programmers. Supplement

Chapter Overview. Pointers and Dynamic Arrays. Pointers. Pointers. Declaring Pointers. Pointers Tell Where To Find A Variable. 9.

Tema 6: Dynamic memory

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Introduction to C++ Systems Programming

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

Complex data types Structures Defined types Structures and functions Structures and pointers (Very) brief introduction to the STL

Object Reference and Memory Allocation. Questions:

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

Declaration Syntax. Declarations. Declarators. Declaration Specifiers. Declaration Examples. Declaration Examples. Declarators include:

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Intermediate Programming, Spring 2017*

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

Name: Username: I. 20. Section: II. p p p III. p p p p Total 100. CMSC 202 Section 06 Fall 2015

Ch 6. Functions. Example: function calls function

Exam 3 Chapters 7 & 9

(6) The specification of a name with its type in a program. (7) Some memory that holds a value of a given type.

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

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)


CMSC 202 Midterm Exam 1 Fall 2015

Computer Programming

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

Sample Final Exam. 1) (24 points) Show what is printed by the following segments of code (assume all appropriate header files, etc.

EL2310 Scientific Programming

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

Module Operator Overloading and Type Conversion. Table of Contents

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

CS201 Latest Solved MCQs

CSE030 Fall 2012 Final Exam Friday, December 14, PM

Class 2: Variables and Memory. Laura Marik Spring 2012 C++ Course Notes (Provided by Jason Minski)

Variables, Memory and Pointers

Bruce Merry. IOI Training Dec 2013

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

Pointers, Dynamic Data, and Reference Types

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Midterm Review. PIC 10B Spring 2018

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

CS2141 Software Development using C/C++ C++ Basics

Constructor - example

Stack memory - "scratch pad" memory that is used by automatic variables.

CSC 211 Intermediate Programming. Arrays & Pointers

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

CSE 303: Concepts and Tools for Software Development

Dynamic Allocation of Memory

CS 376b Computer Vision

Module 7 b. -Namespaces -Exceptions handling

C++: Const Function Overloading Constructors and Destructors Enumerations Assertions

CS201- Introduction to Programming Current Quizzes

BENG (HONS) ELECTRONIC ENGINEERING BENG (HONS) TELECOMMUNICATIONS. Cohort: BEE/10A/FT, BEE/10B/FT &BTEL/10B/FT

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

Pointers and References

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++

COMP 2355 Introduction to Systems Programming

Suppose we find the following function in a file: int Abc::xyz(int z) { return 2 * z + 1; }

cout << "How many numbers would you like to type? "; cin >> memsize; p = new int[memsize];

Extending Classes (contd.) (Chapter 15) Questions:

Lecture on pointers, references, and arrays and vectors

CSE143 Exam with answers MIDTERM #1, 1/26/2001 Problem numbering may differ from the test as given.

Linked List using a Sentinel

Dynamic Allocation of Memory

AN OVERVIEW OF C++ 1

Homework Assignment #2 (revised)

COMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Lab 8 The Stack (LIFO) Structure

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

SORTING AND SEARCHING

Part 1: Introduction to the C Language

TEMPLATE IN C++ Function Templates

Programming in C++: Assignment Week 3

What does it mean by information hiding? What are the advantages of it? {5 Marks}

Arrays and Pointers.

Week 3: Pointers (Part 2)

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

C++ Final Exam 2017/2018

Scheme G. Sample Test Paper-I. Course Name : Computer Engineering Group Course Code : CO/CD/CM/CW/IF Semester : Second Subject Tile : Programming in C

Object oriented programming

Transcription:

Today Todaywewilllookattopicsrelatingtotheuseofpointers USING POINTERS Callbyvalue Call by reference Copy constructors Dynamic memory allocation Thelastoftheseisn tdirectlytodowithpointers,butweneedto coverittounderstandsomeofthestuffthatistodowith pointers. ThismaterialiskindofcoveredinChapter3byPohl. Alltheexamplesinthesenotesareontheclasswebsite. Wewillstartbyrecallingtheuseoffunctions. cis15-fall2007-parsons-lectv.3 2 Functions: parameters and arguments Function header declaration: type name ( parameters ); Function definition: type name ( parameters ) { statements Function invocation: or name ( arguments ); variable_of_type = name ( arguments ): Functionshavetobedeclaredbeforetheycanbecalled Thebookusestheword parameters whenafunctionis declared and arguments when a function is invoked(or called ) Whenafunctioniscalled,theprogramcontrolshiftsfrom wherever the function call originates to the body of the function The function arguments get initialized as local variables within the function. Now, parameters can be either: callbyvalueor call by reference cis15-fall2007-parsons-lectv.3 3 cis15-fall2007-parsons-lectv.3 4

Call by value Withcallbyvalue,thevalueofeachargumentiscopiedtoalocal variable within the function When the function ends, the program control returns to wherever the function was called from, and the memory allocated within the function returns to the program s memory stack Evenifthevaluesofthelocalargumentswithinthefunction changed during the execution of the function, the values that wereusedtoinvokethefunctiondonotchange Example: void myfun( int a ) { a++; cout << "inside myfun, a=" << a << endl; // end of myfun() int a = 7; cout << "before calling myfun, a=" << a << endl; myfun( a ); cout << "after calling myfun, a=" << a << endl; // end of main() cis15-fall2007-parsons-lectv.3 5 cis15-fall2007-parsons-lectv.3 6 Call by reference Theoutputis: before calling myfun, a=7 inside myfun, a=8 after calling myfun, a=7 Withcallbyreference,theaddressofeachargumentiscopiedtoa local variable within the function When the function ends, the program control returns to wherever the function was called from, and the memory allocated within the function returns to the program s memory stack Because the local arguments are addresses, any changes that were made to the values stored at these address locations during the execution of the function are retained when the function ends inc++,therearetwowaystoimplementcallbyreference: using pointers; and using references. cis15-fall2007-parsons-lectv.3 7 cis15-fall2007-parsons-lectv.3 8

Example of call by reference using pointers: void myfun( int *a ) { (*a)++; cout << "inside myfun, *a=" << *a << endl; // end of myfun() int a = 7; cout << "before calling myfun, a=" << a << endl; myfun( &a ); cout << "after calling myfun, a=" << a << endl; Andtheoutputis: before calling myfun, a=7 inside myfun, *a=8 after calling myfun, a=8 cis15-fall2007-parsons-lectv.3 9 cis15-fall2007-parsons-lectv.3 10 Example of call by reference using references: void myfun( int &a ) { a++; cout << "inside myfun, a=" << a << endl; // end of myfun() int a = 7; cout << "before calling myfun, a=" << a << endl; myfun( a ); cout << "after calling myfun, a=" << a << endl; Why use call-by-reference? We use call-be-reference for efficiency. Call-by-value requires the computer to copy the parameters before passing them to the function. Thisisfineiftheparametersareafew charsor doubles. ButinC++wemightcallafunctiononacomplexobjectthat holdsmanymanybytesofdata. Itisfarmoreefficient,inbothmemoryandtime,topassa pointertosuchanobjectthantocopyit. cis15-fall2007-parsons-lectv.3 11 cis15-fall2007-parsons-lectv.3 12

Copy constructors Ifyoudodecidetopassacomplexobjectbycall-by-value,you needtodefineacopyconstructorforit. TheproblemisthatC++onitsdoesn tknowhowtocopy complex objects. Soyouhavetodescribeexactlyhowtomakeacopy. Here s a copy constructor for the point object: point::point(const point& p) { x = p.x; y = p.y; (point is not complex enough to require a copy constructor, but itmakesagoodexamplesinceweknowitsowellbynow). C++knowsthisisacopyconstructorbythesignature. Thereisnoreturntype(justlikeaconstructor). Theonlyargumentisareferencetoanobjectofthesameclassas the constructor is defined for. Usingacopyconstructorwegetadeepcopyoftheoriginalobject. Thisisincontrasttotheshallowcopythatwegetifwedon t define a copy constructor. cis15-fall2007-parsons-lectv.3 13 cis15-fall2007-parsons-lectv.3 14 Passing arrays to functions Given the following example: int sum( int A[], int n ) { int s=0; for ( int i=0; i<n; i++ ) s += A[i]; return( s ); // end of sum() Whenthearray Aispassedtothefunction sum(),itispassed using call-by-value on it s base address(i.e., the address of A[0] However, passing an address call-by-value is the same as passing the thing that is addressed call-by-reference. Thus within the context of a function header definition, the following two statements are equivalent: int sum( int A[],... ) {... and int sum( int *A,... ) {... but not in other contexts! ThisexplainsthefunctionheadersyouseeinsomeoftheC++ libraries. cis15-fall2007-parsons-lectv.3 15 cis15-fall2007-parsons-lectv.3 16

Generic pointers Last class, we talked about pointers to specific data types, e.g.,: Andtheoutputis: before calling myfun, a=7 inside myfun, a=8 after calling myfun, a=8 int *pi; char *pc; Youcanalsohaveapointertoavoid: void *pv; Clearlythisisnotapointer*to*anything(whatisavoid?). A pointertoavoid isagenericpointer. Youcanuseittopointtodifferentkindsofobject. Whenyoudereferencethepointer,itislikeconvertingittothat data type cis15-fall2007-parsons-lectv.3 17 cis15-fall2007-parsons-lectv.3 18 Below are all legal statements, given the definitions above: pv = pi; pv = pc; pi = reinterpret_cast<int*>(pv); *pi = 12; *pc = A ; Youcanuseagenericpointer,forexample,asanargumenttoa functiontowhichoumightneedtopassdifferentkindsofobject. Dynamic memory allocation InC++,therearetwofunctionsthathandledynamicmemory allocation: new and delete Thesyntaxfor newis: newtype-name newtype-nameinitializer newtype-name[expression] For example: int *p, *q, *r; p = new int(5); // allocation and initialization q = new int[10]; // allocation, but uninitialized r = new int; // allocation, but uninitialized Some compilers initialize values to 0 by default, but not all that isnotpartofthelanguagespecification,sodon trelyonit! cis15-fall2007-parsons-lectv.3 19 cis15-fall2007-parsons-lectv.3 20

The syntax for delete is: deleteexpression delete[ ]expression Thefirstformisfornon-arrays;thesecondformisforarrays Thepointofdynamicmemoryallocationistoallowyurprogram todecide,whilerunning,howmuchdataitneedstostore. Youcan,therefore,tailorthesizeofanarraytotheproblemyou are trying to solve. Thenextslidegivesandexample(frombook,p137): int *data; int size; cout << "\nenter array size: "; cin >> size; assert( size > 0 ); data = new int[size]; // allocate array of ints assert( data!= 0 ); for ( int j=0; j<size; j++ ) { cout << (data[j]=j) << \t ; cout << "\n\n"; delete[] data; // deallocate space for array // end of main() cis15-fall2007-parsons-lectv.3 21 cis15-fall2007-parsons-lectv.3 22 Namespaces Youhavealreadybeenusingnamespacesasin: The std namespace is the standard C/C++ namespace that comes with the language Anamespaceisawayofgroupingclassestoavoidnameconflict Thatis,youcouldhavetwothingswiththesamename,butin different name spaces, and then there would be no conflict cis15-fall2007-parsons-lectv.3 23 Declaration of classes within a namespace looks like this: namespace myspace { class myclass1 {... ; class myclass2 {... ; \\ end of namespace Notethatwhenyoudefineanamespaceinaheaderfile,youdo notneedtousethe.hintheincludestatement: versus #include <time.h> Thefirstincludestatementispartofanamespace;thesecondis not cis15-fall2007-parsons-lectv.3 24

Summary Thislecturehaslookedatusesofpointers: We mainly discussed the use of pointers(and references) for call-by-reference. We also described copy constructors; Generic pointers; and Dynamic memory allocation. Finally, we briefly discussed namespaces. cis15-fall2007-parsons-lectv.3 25