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

Similar documents
Chapter 9. Pointers and Dynamic Arrays

Pointers and Dynamic Arrays

In this chapter, you will learn about: Pointers. Dynamic Arrays. Introduction Computer Science 1 CS 23021

What have we learned about when we learned about function parameters? 1-1

Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Chapter 10. Pointers and Dynamic Arrays. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 9. Pointers and Dynamic Arrays. Copyright 2015 Pearson Education, Ltd.. All rights reserved.

Vectors and Pointers CS 16: Solving Problems with Computers I Lecture #13

UEE1302 (1102) F10 Introduction to Computers and Programming (I)

CSC 270 Survey of Programming Languages. What is a Pointer?

Data, memory. Pointers and Dynamic Variables. Example. Pointers Variables (or Pointers) Fall 2018, CS2

Homework #3 CS2255 Fall 2012

Dynamic Arrays Makefiles and Mul3ple File Compiles

Programming in C/C Lecture 2

CSC 211 Intermediate Programming. Arrays & Pointers

A pointer variable has a pointer type, and holds pointer values. If a variable uses a number of adjacent locations, the address of the

Pointers II. Class 31

Chapter 7 Array. Array. C++, How to Program

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

Arrays and Pointers (part 1)

What is an algorithm?

Homework Assignment #2 (revised)

Chapter void Functions. Overview. Functions for All Subtasks. void-functions. Using a void-function. void-function Definition

Pointers. A pointer value is the address of the first byte of the pointed object in the memory. A pointer does not know how many bytes it points to.

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

Arrays and Pointers (part 1)


Goals of this Lecture

Pointers. Variable Declaration. Chapter 10

Arrays, Pointers and Memory Management

C programming Lecture 2. Marina Krstic Marinkovic School of Mathematics Trinity College Dublin

C++ for Engineers and Scientists. Third Edition. Chapter 12 Pointers

Exam 3 Chapters 7 & 9

[0569] p 0318 garbage

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

CPSC 427: Object-Oriented Programming

DYNAMIC ARRAYS; FUNCTIONS & POINTERS; SHALLOW VS DEEP COPY

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Arrays and Pointers. CSE 2031 Fall November 11, 2013

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

Summer May 18, 2010

Reference operator (&)

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

Pointers and References

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.

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

Pointers! Arizona State University 1

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

CPSC 427a: Object-Oriented Programming

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

CA31-1K DIS. Pointers. TA: You Lu

Pointers. Lecture 2 Sections Robb T. Koether. Hampden-Sydney College. Fri, Jan 18, 2013

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Pointers, Dynamic Data, and Reference Types

Pointer Arithmetic. Lecture 4 Chapter 10. Robb T. Koether. Hampden-Sydney College. Wed, Jan 25, 2017

Pointer Assignments. CISC181 Introduction to Computer Science. Dr. McCoy. Lecture 18 October 29, The new Operator

Language comparison. C has pointers. Java has references. C++ has pointers and references

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

Pointers. Lecture 2 Sections Robb T. Koether. Hampden-Sydney College. Mon, Jan 20, 2014

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

CS201 Some Important Definitions

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Today USING POINTERS. Functions: parameters and arguments. Todaywewilllookattopicsrelatingtotheuseofpointers

CS201 Latest Solved MCQs

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Lab # 02. Basic Elements of C++ _ Part1

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Learning Objectives. Introduction to Arrays. Arrays in Functions. Programming with Arrays. Multidimensional Arrays

QUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:

Review of Important Topics in CS1600. Functions Arrays C-strings

Lecture (07) Arrays. By: Dr. Ahmed ElShafee. Dr. Ahmed ElShafee, ACU : Fall 2015, Programming I

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

CSCI 2212: Intermediate Programming / C Review, Chapters 10 and 11

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

C++ for Java Programmers

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

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

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

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2013 CISC2200 Yanjun Li 1. Fall 2013 CISC2200 Yanjun Li 2

Creating a C++ Program

FORM 1 (Please put your name and form # on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

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

Memory and Addresses. Pointers in C. Memory is just a sequence of byte-sized storage devices.

Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

CS 161 Exam II Winter 2018 FORM 1

Arrays and Pointers in C. Alan L. Cox

Lectures 6/7 Pointers and Dynamic Arrays

CS2255 HOMEWORK #1 Fall 2012

Introduction to Programming EC-105. Lecture 2

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

12. Pointers Address-of operator (&)

Object-Oriented Principles and Practice / C++

Pointer Data Type and Pointer Variables

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

EL2310 Scientific Programming

Object Oriented Software Design II

Transcription:

Chapter 9 Pointers and Dynamic Arrays Overview 9.1 Pointers 9.2 Dynamic Arrays Copyright 2011 Pearson Addison-Wesley. All rights reserved. Slide Revised by Zuoliu Ding at Fullerton College, Fall 2011 Slide 9-2 9.1 Pointers Pointers A pointer is the memory address of a variable Memory addresses can be used as names for variables If a variable is stored in four bytes in memory, the address of the first byte can be used as a name for the variable. When a variable is used as a call-by-reference argument, its address is passed Copyright 2008 Pearson Addison-Wesley. All rights reserved. Slide 9-4 Pointers Tell Where To Find A Variable An address used to tell where a variable is stored in memory is a pointer Pointers "point" to a variable by telling where the variable is located Declaring Pointers Pointer variables must be declared to have a pointer type Example: To declare a pointer variable p that can "point" to a variable of type double: double *p; The asterisk identifies p as a pointer variable Slide 9-5 Slide 9-6 1

Multiple Pointer Declarations To declare multiple pointers in a statement, use the asterisk before each pointer variable Example: int *p1, *p2, v1, v2; p1 and p2 point to variables of type int v1 and v2 are variables of type int The address of Operator The & operator can be used to determine the address of a variable which can be assigned to a pointer variable Example: p1 = &v1; p1 is now a pointer to v1 v1 can be called v1 or "the variable pointed to by p1" Slide 9-7 Slide 9-8 The Dereferencing Operator A Pointer Example C++ uses the * operator in yet another way with pointers The phrase "The variable pointed to by p" is translated into C++ as *p Here the * is the dereferencing operator p is said to be dereferenced v1 = 0; p1 = &v1; *p1 = 42; cout << v1 << endl; cout << *p1 << endl; output: 42 42 v1 and *p1 now refer to the same variable Slide 9-9 Slide 9-10 Pointer Assignment The assignment operator = is used to assign the value of one pointer to another Example: If p1 still points to v1 (previous slide) then p2 = p1; causes *p2, *p1, and v1 all to name the same variable Caution! Pointer Assignments Some care is required making assignments to pointer variables p1= p3; // changes the location that p1 "points" to *p1 = *p3; // changes the value at the location that // p1 "points" to Display 9.1 Slide 9-11 Slide 9-12 2

The new Operator Using pointers, variables can be manipulated even if there is no identifier for them To create a pointer to a new "nameless" variable of type int: p1 = new int; The new variable is referred to as *p1 *p1 can be used anyplace as an integer variable can cin >> *p1; *p1 = *p1 + 7; Dynamic Variables Variables created using the new operator are called dynamic variables Dynamic variables are created and destroyed while the program is running Additional examples of pointers and dynamic variables are shown in Display 9.2 An illustration of the code in Display 9.2 is seen in Display 9.3 Slide 9-13 Slide 9-14 new and Class Types Using operator new with class types calls a constructor as well as allocating memory If MyType is a class type, then MyType *myptr; // creates a pointer to a // variable of type MyType myptr = new MyType; // calls the default constructor myptr = new MyType (32.0, 17); // calls Mytype(double, int); Basic Memory Management An area of memory called the free store is reserved for dynamic variables New dynamic variables use memory in the free store If all free store is used, calls to new will fail Unneeded memory can be recycled When variables are no longer needed, they can be deleted and the memory they used is returned to the free store Slide 9-15 Slide 9-16 The delete Operator When dynamic variables are no longer needed, delete them to return memory to the free store Example: delete p; The value of p is now undefined and the memory used by the variable that p pointed to is back in the free store Dangling Pointers Using delete on a pointer variable destroys the dynamic variable pointed to If another pointer variable was pointing to the dynamic variable, that variable is also undefined Undefined pointer variables are called dangling pointers Dereferencing a dangling pointer (*p) should be avoided Slide 9-17 Slide 9-18 3

Automatic Variables Variables declared in a function are created by C++ and destroyed when the function ends These are called automatic variables because their creation and destruction is controlled automatically The programmer manually controls creation and destruction of pointer variables with operators new and delete Global Variables Variables declared outside any function definition are global variables Global variables are available to all parts of a program Global variables are not generally recommended in learning programming Slide 9-19 Slide 9-20 Type Definitions A name can be assigned to a type definition, then used to declare variables The keyword typedef is used to define new type names Syntax: typedef Known_Type_Definition New_Type_Name; Known_Type_Definition can be any type Defining Pointer Types To avoid mistakes using pointers, define a pointer type name Example: typedef int* IntPtr; Defines a new type, IntPtr, for pointer variables containing pointers to int variables IntPtr p; is equivalent to int *p; Slide 9-21 Slide 9-22 Multiple Declarations Again Using our new pointer type defined as typedef int* IntPtr; Prevent this error in pointer declaration: int *P1, P2; // Only P1 is a pointer variable Both P1 and P2 are pointer variables IntPtr P1, P2; It s not a replacement using int* for IntPtr Pointer Reference Parameters A second advantage in using typedef to define a pointer type is seen in parameter lists Example: void sample_function(intptr& pointer_var); is less confusing than void sample_function( int*& pointer_var); Slide 9-23 Slide 9-24 4

Section 9.1 Conclusion Can you Declare a pointer variable? Assign a value to a pointer variable? Use the new operator to create a new variable in the freestore? Write a definition for a type called NumberPtr to be a type for pointers to dynamic variables of type int? Use the NumberPtr type to declare a pointer variable called my_point? 9.2 Dynamic Arrays Slide 9-25 Copyright 2008 Pearson Addison-Wesley. All rights reserved. Dynamic Arrays A dynamic array is an array whose size is determined when the program is running, not when you write the program Pointer Variables and Array Variables Array variables are actually pointer variables that point to the first indexed variable Example: int a[10]; typedef int* IntPtr; IntPtr p; Variables a and p are the same kind of variable Since a is a pointer variable that points to a[0], p = a; causes p to point to the same location as a Slide 9-27 Slide 9-28 Pointer Variables As Array Variables Continuing the previous example: Pointer variable p can be used as if it were an array variable Display 9.4 Example: p[0], p[1], p[9] are all legal ways to use Display 9.5 p Variable a can be used as a pointer variable except the pointer value in a cannot be changed This is not legal: IntPtr p2; // p2 is assigned a value a = p2 // attempt to change a Swap array elements with pointers // swap a[3] with a[7] with pointers p = a+3; // the same as &a[3]; int *q = a+7; // the same as &a[7]; int n = *p; *p = *q; *q = n; // awap a[0] with a[2] with the array name n = *a; // the same as a[0]; *a = *(a+2); // the same as a[2] *(a+2) = n; Slide 9-29 Zuoliu Ding Slide 9-30 5

Creating Dynamic Arrays Normal arrays require that the programmer determine the size of the array when the program is written What if the programmer estimates too large? Memory is wasted What if the programmer estimates too small? The program may not work in some situations Dynamic arrays can be created with just the right size while the program is running Creating Dynamic Arrays Dynamic arrays are created using new operator Example: To create an array of 10 elements of type double: typedef double* DoublePtr; DoublePtr d; d = new double[10]; This could be an integer variable! d can now be used as if it were an ordinary array! Slide 9-31 Slide 9-32 Dynamic Arrays (cont.) Pointer variable d is a pointer to d[0] When finished with the array, it should be deleted to return memory to the free store Example: delete [ ] d; The brackets tell C++ a dynamic array is being deleted so it must check the size to know how many indexed variables to remove Forgetting the brackets, is not legal, but would Display 9.6 (1) remove only one variable Display 9.6 (2) Pointer Arithmetic Arithmetic can be performed on the addresses contained in pointers Using the dynamic array of doubles, d, declared previously, recall that d points to d[0] The expression d+1 evaluates to the address of d[1] and d+2 evaluates to the address of d[2] Notice that adding one adds enough bytes for one variable of the type stored in the array Slide 9-33 Slide 9-34 Pointer Arthmetic Operations You can add and subtract with pointers The ++ and - - operators can be used Two pointers of the same type can be subtracted to obtain the number of indexed variables The pointers should be in the same array! This code shows a way to use pointer arithmetic: for (int i = 0; i < array_size; i++) cout << *(d + i) << " " ; // same as cout << d[i] << " " ; Pointer ++ and -- Operations You can use ++ or -- with pointers The ++ and - - operators skip one element not one byte If a is an array and p=a; You can p++ but cannot a++ Slide 9-35 Zuoliu Ding Slide 9-36 6

Return an Array from a Function int* f(int n) { int *p = new int[3]; for (int i=0; i<3; i++) p[i] = i+n; return p; } int main( ) { int *a = f(11); for (int i=0; i<3; i++) cout << a[i] << " "; cout << endl; return 0; } Multidimensional Dynamic Arrays To create a 3x4 multidimensional dynamic array View multidimensional arrays as arrays of arrays First create a one-dimensional dynamic array Start with a new definition: typedef int* IntArrayPtr; Now create a dynamic array of pointers named m: IntArrayPtr *m = new IntArrayPtr[3]; For each pointer in m, create a dynamic array of int's for (int i = 0; i<3; i++) m[i] = new int[4]; Zuoliu Ding Slide 9-37 Slide 9-38 A Multidimensional Dynamic Array The dynamic array created on the previous slide could be visualized like this: m IntArrayPtr * IntArrayPtr's Deleting Multidimensional Arrays To delete a multidimensional dynamic array Each call to new that created an array must have a corresponding call to delete[ ] Example: To delete the dynamic array created on a previous slide: for ( i = 0; i < 3; i++) delete [ ] m[i]; //delete the arrays of 4 int's delete [ ] m; // delete the array of IntArrayPtr's int's Display 9.7 (1) Display 9.7 (2) Slide 9-39 Slide 9-40 Section 9.2 Conclusion Display 9.1 Can you Write a definition for pointer variables that will be used to point to dynamic arrays? The array elements are of type char. Call the type CharArray. Write code to fill array "entry" with 10 numbers typed at the keyboard? int * entry; entry = new int[10]; Slide 9-41 Slide 9-42 7

Display 9.2 Display 9.3 Slide 9-43 Slide 9-44 Display 9.4 Display 9.5 Slide 9-45 Slide 9-46 Display 9.6 (1/2) Display 9.6 (2/2) Slide 9-47 Slide 9-48 8

Display 9.7 (1/2) Display 9.7 (2/2) Slide 9-49 Slide 9-50 9