Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Copyright © 2003 Pearson Education, Inc. Slide 1.
Chapter 10 Pointers and Dynamic Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives Pointers Pointer variables.
Etter/Ingber Arrays and Matrices. Etter/Ingber One-Dimensional Arrays 4 An array is an indexed data structure 4 All variables stored in an array are of.
Call By Address Parameters (Pointers) Chapter 5. Functions that “return” more than a single value What if we need more than one value to be returned from.
Introduction to Programming Lecture 15. In Today’s Lecture Pointers and Arrays Manipulations Pointers and Arrays Manipulations Pointers Expression Pointers.
Derived data types Dealing with data –Where the information is stored –What value is kept there –What kind of information is stored Address operator Pointers.
A pointer is the memory address of a variable. A memory address is a physical location within a system’s memory space. A pointer variable is variable used.
Dynamic Memory Allocation (also see pointers lectures) -L. Grewe.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
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.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Copyright 2004 Scott/Jones Publishing Starting Out with C++: Early.
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.
Pointers 1 Pointers Pointers  In chapter three we looked at passing parameters to functions using call by value, and using call by reference, using reference.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 9: Pointers.
Copyright © 2012 Pearson Education, Inc. Chapter 9: Pointers.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Dynamic Memory Allocation 9.8.
Comp 245 Data Structures Linked Lists. An Array Based List Usually is statically allocated; may not use memory efficiently Direct access to data; faster.
7. Pointers, Dynamic Memory 20 th September IIT Kanpur 1C Course, Programming club, Fall 2008.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 9: Pointers.
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
 2003 Prentice Hall, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate pass-by-reference –Close relationship.
CSC 107 – Programming For Science. Today’s Goal  When lecture over, start understanding pointers  What a pointer is and what it is not  Why pointers.
Pointers Pointers are a unique class of variables whose purpose is to “point” to other variables Pointers allow programmers direct access to memory addresses.
CSC 107 – Programming For Science. Today’s Goal  When lecture over, start understanding pointers  What a pointer is and what it is not  Why pointers.
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.
Pointers in C++. 7a-2 Pointers "pointer" is a basic type like int or double value of a pointer variable contains the location, or address in memory, of.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Chapter 11 – Pointer Variables. Declaring a Pointer Variable u Declared with data type, * and identifier type* pointer_variable; u * follows data type.
C++ Programming Lecture 17 Pointers – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
C Programming Lecture 16 Pointers. Pointers b A pointer is simply a variable that, like other variables, provides a name for a location (address) in memory.
Lecture 17: The Last Puzzle Piece with Functions.
Lecture – Pointers1 C++ Pointers Joseph Spring/Bob Dickerson School of Computer Science Operating Systems and Computer Networks Based on notes by Bob Dickerson.
+ Pointers. + Content Address of operator (&) Pointers Pointers and array.
Pointers in C++. Topics Covered  Introduction to Pointers  Pointers and arrays  Character Pointers, Arrays and Strings  Examples.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman CP 202 Chapter 6.
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.
Engineering Computing I Chapter 5 Pointers and Arrays.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
POINTERS IN C. Introduction  A pointer is a variable that holds a memory address  This address is the location of another object (typically another.
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 7 – Pointers.
ADVANCED POINTERS. Overview Review on pointers and arrays Common troubles with pointers Multidimensional arrays Pointers as function arguments Functions.
Pointers in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Pointers  * symbol and & symbol  Pointer operations  Pointer.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
C++ for Engineers and Scientists Second Edition Chapter 12 Pointers.
POINTERS AND MEMORY ACKNOWLEDGEMENT: THE SLIDES ARE PREPARED FROM SLIDES PROVIDED BY NANCY M. AMATO AND JORY DENNY 1.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
Pointers What is the data type of pointer variables?
Pointers and Dynamic Arrays
© 2016 Pearson Education, Ltd. All rights reserved.
Pointers Psst… over there.
Pointer Data Type and Pointer Variables
14th September IIT Kanpur
Pointers Psst… over there.
Pointer Basics Psst… over there.
Chapter 9: Pointers.
Chapter 9: Pointers.
Alternate Version of STARTING OUT WITH C++ 4th Edition
Pointers And Memory Acknowledgement: THE Slides are Prepared FROM SLIDES PROVIDED By NANCY M. AMATO AND Jory Denny.
C Programming Pointers
Pointers and dynamic objects
Pointer Data Type and Pointer Variables
Pointer Basics Psst… over there.
Pointer Data Type and Pointer Variables
Introduction to Pointers
Presentation transcript:

Chapter 9 Pointers and Dynamic Arrays

Overview 9.1 Pointers 9.2 Dynamic Arrays

9.1 Pointers

Pointers n A pointer is the memory address of a variable n Memory addresses can be used as names for variables – If a variable is stored in three memory locations, the address of the first can be used as a name for the variable. – When a variable is used as a call-by-reference argument, its address is passed

Pointers Tell Where To Find A Variable n 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 n 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

Multiple Pointer Declarations n 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 n 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"

The Dereferencing Operator n 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 n p is said to be dereferenced

v1 and *p1 now refer to the same variable A Pointer Example n v1 = 0; p1 = &v1; *p1 = 42; cout << v1 << endl; cout << *p1 << endl; output: 42 42

Pointer Assignment n 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 n Some care is required making assignments to pointer variables – p1= p2; // changes the location that p1 "points" to – *p1 = *p2; // changes the value at the location that p1 "points" to

The new Operator n 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 an integer variable can cin >> *p1; *p1 = *p1 + 7;

n 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 An illustration of the code in Display 9.2 is seen in Dynamic Variables

new and Class Types …. Not Now n 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 n An area of memory called the freestore is reserved for dynamic variables – New dynamic variables use memory in the freestore – If all of the freestore is used, calls to new will fail n Unneeded memory can be recycled – When variables are no longer needed, they can be deleted and the memory they used is returned to the freestore

The delete Operator n When dynamic variables are no longer needed, delete them to return memory to the freestore – 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 freestore

Dangling Pointers n Using delete on a pointer variable destroys the dynamic variable pointed to n If another pointer variable was pointing to the dynamic variable, that variable is also undefined n Undefined pointer variables are called dangling pointers – Dereferencing a dangling pointer (*p) is usually disasterous

Automatic Variables n 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 n The programmer manually controls creation and destruction of pointer variables with operators new and delete

Global Variables n Variables declared outside any function definition are global variables – Global variables are available to all parts of a program – Global variables are not generally used

Type Definitions n A name can be assigned to a type definition, then used to declare variables n The keyword typedef is used to define new type names – Syntax: – typedef Known_TypeDefinition New_Type_Name; n Known_Type_Definition can be any type

Defining Pointer Types n 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;

Multiple Declarations Again n 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 n with IntPtr P1, P2; // P1 and P2 are pointer // variables

Pointer Reference Parameters n 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);

9.2 Dynamic Arrays

Dynamic Arrays n 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 n Array variables are actually pointer variables that point to the first indexed variable – Example: int a[10]; typedef int* IntPtr; IntPtr p; n Variables a and p are the same kind of variable n Since a is a pointer variable that points to a[0], p = a; causes ‘p’ to point to the same location as ‘a’

– Continuing the previous example: Pointer variable p can be used as if it were an array variable – Example: p[0], p[1], …p[9] are all legal ways to use p – Variable a can be used as a pointer variable except the pointer value in a cannot be changed n This is not legal: IntPtr p2; … // p2 is assigned a value a = p2 // attempt to change a Pointer Variables As Array Variables

Creating Dynamic Arrays n Normal arrays require that the programmer determine the size of the array when the program is written – What if the programmer estimates too large? n Memory is wasted – What if the programmer estimates too small? n The program may not work in some situations n Dynamic arrays can be created with just the right size while the program is running

n Dynamic arrays are created using the new operator – Example: To create an array of 10 elements of type double: typedef double* DoublePtr; DoublePtr d; d = new double[10]; n d can now be used as if it were an ordinary array! This could be an integer variable! Creating Dynamic Arrays

n Pointer variable d is a pointer to d[0] n When finished with the array, it should be deleted to return memory to the freestore – Example: delete [ ] d; n The brackets tell C++ a dynamic array is being deleted so it must check the size to know how many indexed variables to remove n Forgetting the brackets, is not illegal, but would tell the computer to remove only one variable Dynamic Arrays (cont.)

Pointer Arithmetic (Optional) n 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] n Notice that adding one adds enough bytes for one variable of the type stored in the array

Pointer Arthmetic Operations n 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 between n The pointers should be in the same array! – This code shows one way to use pointer arithmetic: for (int i = 0; i < array_size; i++) cout << *(d + i) << " " ; // same as cout << d[i] << " " ;

Multidimensional Dynamic Arrays n To create a 3x4 multidimensional dynamic array – View multidimensional arrays as arrays of arrays – First create a one-dimensional dynamic array n Start with a new definition: typedef int* IntArrayPtr; n 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 n for (int i = 0; i<3; i++) m[i] = new int[4];

m IntArrayPtr's int's IntArrayPtr * A Multidimensial Dynamic Array n The dynamic array created on the previous slide could be visualized like this:

n 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 Deleting Multidimensional Arrays

Pointer to a String n char * terry = "hello"; n In this case, memory space is reserved to contain "hello" and then a pointer to the first character of this memory block is assigned to terry. If we imagine that "hello" is stored at the memory locations that start at addresses 1702, we can represent the previous declaration as:

n char a; n char * b; n char ** c; n a = 'z'; n b = &a; n c = &b;

Void Pointers n The void type of pointer is a special type of pointer. In C++, void represents the absence of type, so void pointers are pointers that point to a value that has no type (and thus also an undetermined length and undetermined dereference properties). n This allows void pointers to point to any data type, from an integer value or a float to a string of characters. n But in exchange they have a great limitation: the data pointed by them cannot be directly dereferenced (which is logical, since we have no type to dereference to), and for that reason we will always have to cast the address in the void pointer to some other pointer type that points to a concrete data type before dereferencing it.

Void Pointer // increaser #include using namespace std; void increase (void* data, int psize) { if ( psize == sizeof(char) ) { char* pchar; pchar=(char*)data; ++(*pchar); } else if (psize == sizeof(int) ) { int* pint; pint=(int*)data; ++(*pint); } int main () { char a = 'x'; int b = 1602; increase (&a,sizeof(a)); increase (&b,sizeof(b)); cout << a << ", " << b << endl; return 0; }

Null pointer n A null pointer is a regular pointer of any pointer type which has a special value that indicates that it is not pointing to any valid reference or memory address. This value is the result of type-casting the integer value zero to any pointer type. n int * p; p = 0; // p has a null pointer value n A null pointer is a value that any pointer may take to represent that it is pointing to "nowhere", while a void pointer is a special type of pointer that can point to somewhere without a specific type. One refers to the value stored in the pointer itself and the other to the type of data it points to.