77
COMP103 - Pointers 1 This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson Learning, 2000. Pointers (Chapter 9) A pointer keeps the address of a memory cell that is used for storing and accessing data int a;

Pointers (Chapter 9)

Embed Size (px)

DESCRIPTION

int a;. Pointers (Chapter 9). A pointer keeps the address of a memory cell that is used for storing and accessing data. Why Pointers?. Curious – like to know where exactly is your variable in memory, the content of a certain memory location. - PowerPoint PPT Presentation

Citation preview

Page 1: Pointers (Chapter 9)

COMP103 - Pointers 1

This set of notes is adapted from that provided by “Computer Science – A Structured Programming Approach Using C++”, B.A. Forouzan & R.F. Gilberg, Thomson Learning, 2000.

Pointers (Chapter 9)

A pointer keeps the address of a memory cell that is used for storing and accessing data

int a;

Page 2: Pointers (Chapter 9)

COMP103 - Pointers 2

Why Pointers?

1. Curious – like to know where exactly is your variable in memory, the content of a certain memory location.

2. Not sure how much memory you need for your program

int A[size];

Page 3: Pointers (Chapter 9)

COMP103 - Pointers 3

Computer Memory

Memory can be conceptualized as a linear set of “cells” (one byte in size) with a number, referred to as “address” associated with each cell.

Memory cellsVariables Address

a

000000

000001

000002achar

Page 4: Pointers (Chapter 9)

COMP103 - Pointers 4

Variables’ data are stored in these cells

int a = 10;

char mystr[5]=“hello”;

Variable Data and Memory

Note: Different types of data require different amountsof memory

Computer Memory

00 00 11 00

hh ee ll ll oo

4 bytes

5 single bytes

Page 5: Pointers (Chapter 9)

COMP103 - Pointers 5

Variables’ data are stored in these cells

char mystr[]=“hello”;

int a = 10;

a = 20;

Variable Data and Memory

An assignment changes the data in the memory location

Variable a is bound to this memory location!

Computer Memory

00 00 22 00

hh ee ll ll oo

4 bytes

5 single bytes

Page 6: Pointers (Chapter 9)

COMP103 - Pointers 6

Pointer Constants (or memory address)

We can think memory addresses as Pointer Constants

Pointer Constants

int a = 10;

1048575

1048574

1048573

000000

000001

00004000

To004003

00 11 00

Page 7: Pointers (Chapter 9)

COMP103 - Pointers 7

Address Operator (&)

Address operator (&) provides a pointer constant of the variable: usage &variable_name

Pointer Constants

int a = 10; &a 004000

1048575

1048574

1048573

000000

000001

00004000

To004003

00 11 00

Page 8: Pointers (Chapter 9)

COMP103 - Pointers 8

Figure 9-4(p.415)

Address Operator &

&variable gives the address of the variable &a and &b.

Result: 142300 142301 (note: this does not work in Visual C++!!)

Variable name

Address

Page 9: Pointers (Chapter 9)

COMP103 - Pointers 9

Pointer Variable A pointer variable is a

variable that stores a memory location (address)

Pointers are declared using a “*” after the type

int a = 10;

// a pointer variable!!!

int *p;

p = &a;

Pointer Constants

a

p

1048575

1048574

1048573

000000

000001

00004000

To004003

00 11 00

4 0 0 0

Page 10: Pointers (Chapter 9)

COMP103 - Pointers 10

Pointer Variable Declaration

Type of data at the Memory location

Figure 9-10

(p.419)

Variable Name

Page 11: Pointers (Chapter 9)

COMP103 - Pointers 11

Declaring Pointer VariablesFigure 9-11

(p.419)

Page 12: Pointers (Chapter 9)

COMP103 - Pointers 12

Don’t get confused

Pointer variable, p does not hold the value of a

points to the memory location of a

is a variable itself has its own memory

location (1002300)

Pointer Constants

a

p

1048575

1048574

1048573

000000

000001

00004000

To004003

00 11 00

4 0 0 0 1002300

int a;

int *p;

a=10;

P = &a;

Page 13: Pointers (Chapter 9)

COMP103 - Pointers 13

Multiple Pointers to a Variable

We may have multiple pointer variables pointing to the same memory cell!

What are their values? a = ? &a = ? p = ? q = ?

Figure 9-7

(p.417)

Page 14: Pointers (Chapter 9)

COMP103 - Pointers 14

Multiple Pointers to One Variable

How?

int a, *p, *q, *r;p = &a;q = &a;r = q;

Figure 9-6

(p.425)

Page 15: Pointers (Chapter 9)

COMP103 - Pointers 15

Multiple Pointers to a Variable

int x;int *p, *q;

p = &x; q = &x;

Changing the variable x does not affect the pointers p and q

Figure 9-8

(p.418)

Page 16: Pointers (Chapter 9)

COMP103 - Pointers 16

Un-initialized PointersFigure 9-12

(p.421)

Page 17: Pointers (Chapter 9)

COMP103 - Pointers 17

Initialize Pointer Variables

int *p = &x;

// set a pointer to nothing int *p = NULL;

Figure 9-13

(p.421)

Page 18: Pointers (Chapter 9)

COMP103 - Pointers 18

Multiple Bindings

The power of pointers! A pointer may be used to access

different variables.

p = &a

p = &b p = &c

Figure 9-15

(p.424)

Page 19: Pointers (Chapter 9)

COMP103 - Pointers 19

Using pointers - Indirection (*)

We can use the pointer variable to access the variable it “points” to by

Placing a * before a pointer variable, p refers to the content of the address of the variable given in p.

int a, *p;a=5;

p = &a; cout << p << *p;

Result: 100203 5

This is sometimes called “ de-referencing” the pointer

5a 100203

p 100203

Address

Page 20: Pointers (Chapter 9)

COMP103 - Pointers 20

Address Operator (&) and Indirection (*)

&& **inverse

operators

Example:int x=5;cout << *(&x); // *(&x) is just x

IndirectionAddressOperator

&a reads “give me the memory address of the variable a”

*p reads “give me the content of the memory address which is stored in the pointer variable p”

Page 21: Pointers (Chapter 9)

COMP103 - Pointers 21

Indirection Operator *

Using the indirection operator * Assume: p = &x; Possible ways of adding 1 to variable x:

x++; x = x + 1; *p = *p + 1;

Page 22: Pointers (Chapter 9)

COMP103 - Pointers 22

Add Two Numbers using Pointers

How do we achieve the following effects using pointers?

r = a + b

Figure 9-14

(p.423)

Page 23: Pointers (Chapter 9)

COMP103 - Pointers 23

More Examples

Assume: int *p, *q; p = &x; q = &x;Figure 9-8

(p.418)

Page 24: Pointers (Chapter 9)

COMP103 - Pointers 24

Dereferencing garbage pointers

int a = 0;

int *p;

a = a + *p; // What will happen????

Page 25: Pointers (Chapter 9)

COMP103 - Pointers 25

References vs. Pointers

SUPERMAN (same person [reference])CLARK KENT

PERSON (Pointing to Superman [two different people])

*PERSON = Superman (What is he pointing to? Superman)

Page 26: Pointers (Chapter 9)

COMP103 - Pointers 26

References versus Pointers

Reference and pointers are different

a

num

memory

A reference shares thesame memory location withother variables.

int a;int &num = a; // num IS a

A pointer is a variable.It points to a memory location.You have to use the (*)indirection operator to accessthe memory location at ‘a’;

int a;int *p = &a;Cout << *p // same a

a p

6 6

Page 27: Pointers (Chapter 9)

COMP103 - Pointers 27

Parameter Passing - by Value

Variables a and x use different memory cells.

differentcopies

Figure 9-17(a)

(p.426)

Page 28: Pointers (Chapter 9)

COMP103 - Pointers 28

samecopy

Parameter Passing - by Reference

Variables a and x share the same memory cell.

Figure 9-17(b)

(p.426)

Page 29: Pointers (Chapter 9)

COMP103 - Pointers 29

Parameter Passing - by Pointers

Pointer variables, px and py refer to the memory cells of a and b.

Figure 9-17(c)

(p.417)

Page 30: Pointers (Chapter 9)

COMP103 - Pointers 30

Pointers as Formal Parameters

When we use pointer variables as formal parameters, we achieve the same effects of parameter passing by reference.

by-reference: void exchange(int &x, int &y)

by-pointer: void exchange(int *px, int *py)

Page 31: Pointers (Chapter 9)

COMP103 - Pointers 31

Functions Returning Pointers

Figure 9-18

(p.427)

Page 32: Pointers (Chapter 9)

COMP103 - Pointers 32

Note in returning pointers Never return a

pointer to a local variable. You’ll get a warning message

Must point to a variable in the calling function

void main(){ int a, b, *p; … p = smaller( &a, &b ); …}

int *smaller (int *px, int *py){ int temp = (*px < *py)? *px : *py; return (&temp);}

This is bad! Don’t do it.

Page 33: Pointers (Chapter 9)

COMP103 - Pointers 33

Pointer Indirection (Pointers to Pointers)

What is

a? &a? *a?

p? &p? *p? **p?

q? &q? *q? **q?58

Figure 9-19

(p.428)

Page 34: Pointers (Chapter 9)

COMP103 - Pointers 34

Pointers Indirection

How to access a from p? *p How to access a from q? **q How to access a from r? ***r

Figure 9-20

(p.429)

58

Page 35: Pointers (Chapter 9)

COMP103 - Pointers 35

Casting Pointers (DO NOT DO!) What if we want

to have pc pointing to a?

Warning: You're advised not to cast pointers unless absolutely necessary.

pc = (char *) &a;

Figure 9-21

(p.433)

Page 36: Pointers (Chapter 9)

COMP103 - Pointers 36

Pointer Types Must MatchFigure 9-22

(p.433)

Page 37: Pointers (Chapter 9)

COMP103 - Pointers 37

Lvalue vs Rvalue (Ch 9-10,p.434-436)

An C++ expression is either a rvalue or lvalue. A rvalue expression appears at the right of an

assignment. It refers to a value that be assigned to a memory cell, i.e. can be used to supply a value for further use, e.g. examine or copy the value. Examples: x= 5; y= a+2; z=a*6; x=a[2]+3; i=i+

+; A lvalue expression appears at the left of an

assignment. It identifies a memory cell that is going to receive a rvalue, i.e. the memory cell is being modified. Example: a = … a[5] = … (a) = … *p = …

Page 38: Pointers (Chapter 9)

COMP103 - Pointers 38

Arrays and Pointers The name of an array points only to the first

element not the whole array, i.e. the variable name of an array is a pointer variable.

Figure 9-25

(p.443)

Page 39: Pointers (Chapter 9)

COMP103 - Pointers 39

Array Name is a pointer constantExample on p.443 of text

(where is the array in memory?)

#include <iostream.h>void main(){ // Demonstrate array name is a pointer constant int a[5]; cout << "Address of a[0]: " << &a[0] << endl

<< "Name as pointer: " << a << endl;}

/* result:Address of a[0]: 0x0065FDE4Name as pointer: 0x0065FDE4*/

Page 40: Pointers (Chapter 9)

COMP103 - Pointers 40

Dereference of An Array Name

Figure 9-26

(p.444)

How to obtain the value of a[0] using pointer operator, “*”?

Page 41: Pointers (Chapter 9)

COMP103 - Pointers 41

Array Names as Pointers

To access an array, any pointer to the first element can be used instead of the name of the array.

We could replace *p by *a

Figure 9-27

(p.444)

Page 42: Pointers (Chapter 9)

COMP103 - Pointers 42

Multiple Array Pointers Both a and p are pointers to the same array.

Figure 9-28

(p.445)

Page 43: Pointers (Chapter 9)

COMP103 - Pointers 43

Pointer Arithmetic

Given a pointer p, p+n refers to the element that is offset from p by n positions. Figure 9-29

(p.446)

Page 44: Pointers (Chapter 9)

COMP103 - Pointers 44

Pointer Arithmetic & Different Types

address = pointer + (offset * size of element)

Figure 9-30

(p.446)

Page 45: Pointers (Chapter 9)

COMP103 - Pointers 45

*(a+n) is identical to a[n]

Dereferencing Array PointersFigure 9-31

(p.447)

Page 46: Pointers (Chapter 9)

COMP103 - Pointers 46

Pointers—Arrays Duality

int a[10];

You can think of ‘a’ as really a pointer.

a[0] = *(a+0) = memory at (a+0) a[1] = *(a+1) = memory at (a+1) a[2] = *(a+2) = memory at (a+2)

Page 47: Pointers (Chapter 9)

COMP103 - Pointers 47

Example:Find Smallest(Figure 9-32, p.447)

Figure 9-32

(p.447)

Page 48: Pointers (Chapter 9)

COMP103 - Pointers 48

Pointer to 2-Dimensional Arrays

table[i][j]What is **table?

Figure 9-33

(p.450)

Page 49: Pointers (Chapter 9)

COMP103 - Pointers 49

Passing an Array to a Function Caller program:

func( arrayName, size );

Called program: int func( int arr [ ], int size ) {…} // preferred

or

int func( int *arr, int size ) {…} // same effect

Arrays are passed to a function by reference.

Page 50: Pointers (Chapter 9)

COMP103 - Pointers 50

Variables for Multiplying Array Elements by Two

Figure 9-34

(p.452)

Program 9-12

(p.452)

Page 51: Pointers (Chapter 9)

COMP103 - Pointers 51

Right-Left Rule Concept

int * p; reads “p is a pointer (2) to integer (4)” int table [4]; reads “table is an array of 4 (1) integers (2)” int *a[5]; reads “a is an array of 5 (1) pointers (2) to integer (4)” int ( *a )[5]; reads “a is a pointer (2) to an array of 5 (3) integers (4)”

(page 454)

Page 52: Pointers (Chapter 9)

COMP103 - Pointers 52

Array of Pointers & Pointer to Array

Page 53: Pointers (Chapter 9)

COMP103 - Pointers 53

MEMORY MANAGEMENT

DYANMIC MEMORY

STATIC MEMORY•Until now, we have only learned about static memory

•Declaration of large memory variables (arrays) must be determined before the program is compiled.

•We can “ask” for memory while the program is running.

•We can allocate and release memory ourselves!

•More powerful programming ability (also more potential for errors!)

Page 54: Pointers (Chapter 9)

COMP103 - Pointers 54

Memory Allocation

{ int a[200]; int *ptr = a; …}

int *ptr = new int[200];…delete [] ptr;

Figure 9-35

(p.455)

Page 55: Pointers (Chapter 9)

COMP103 - Pointers 55

Conceptual View of Memory

(DYNAMIC MEMORY)

Figure 9-37

(p.456)

Page 56: Pointers (Chapter 9)

COMP103 - Pointers 56

Dynamic Memory

C++ “new” keywordnew <type>; // allocate size of the type new <type>[size]; // allocate an array

Asks the Operating System to return you a pointer to a “chunk” of data.

Page 57: Pointers (Chapter 9)

COMP103 - Pointers 57

Allocating MemoryOperating System

Manages dynamicmemory.

You have:

int *p;

p = new int[1000];

Ask OS to find a segmentOf memory of 1000*4 btyes

OS returnsthe address.

So, you need a pointer to the type you requested.If you request <int>, you need an <int> pointer.

If you request <float>, you need a <float> pointer.If you request <float *>, you need a <float *> pointer.

Page 58: Pointers (Chapter 9)

COMP103 - Pointers 58

Allocating memory using “new”

int *p;

8002

8006

8010

8014

8018

8022

8026

new returns the address to the“start” of the memory it allocated

p = new int[7];

p is assigned 8002

p[0] = *(p) = *(p+0) = ?p[1] = *(p+1) = ?p[2] = *(p+2) = ?

p[0]

p[1]

p[2]

Page 59: Pointers (Chapter 9)

COMP103 - Pointers 59

Dynamic Memory Allocation

Request for “unused” memory from the Operating System

int *p, n=10;

p = new int;

p = new int[100];

p = new int[n];

pnew

pnew

pnew

Page 60: Pointers (Chapter 9)

COMP103 - Pointers 60

Dynamic Memory Allocation Example

Need an array of unknown sizemain(){ cout << “How many students? “; cin >> n;

int *grades = new int; int mark; int i; for(i=0; i < n; i++) { cout << “Input Grade for Student” << (i+1) << “ ? :”; cin >> mark; grades[i] = mark; }

. . . printMean( grades, n ); // call a function with dynamic array . . . }

Page 61: Pointers (Chapter 9)

COMP103 - Pointers 61

Dynamic Memory

C++ “delete” keyword

delete address; // delete one element at address

delete [] address; // delete array at address

How can we specify what the address is?We have pointer. Pointer variables storeaddresses.

Page 62: Pointers (Chapter 9)

COMP103 - Pointers 62

Freeing (or deleting) MemoryOperating System

Manages dynamicmemory.

The memory you request by “new” is not usable byOther programs until you tell the OS you don’t need it anymore.We call this “freeing” or “releasing” or “deleting” memory.

How does the OS know which piece of memory you are freeing?

You give it the address.

Int *p;

p = new int [1000];

delete [] p; // delete (or free) the array at p

NOTICE, the value of p will not change! However, it is now no longerpointer to value memory.

AllocatedMemory

Free this Memory.OS marksit as available.

Page 63: Pointers (Chapter 9)

COMP103 - Pointers 63

Freeing (or deleting) Memory

Figure 9-40

(p.460)

Page 64: Pointers (Chapter 9)

COMP103 - Pointers 64

Freeing (or Deleting) memory “ delete” is a keyword

delete <address, i.e. pointer variable>; // a variable example:

int a; int *p=&a; delete p;

delete [] <address, i.e. pointer variable>; // an array example:

int *p = new int[1000]; delete [] p;

Page 65: Pointers (Chapter 9)

COMP103 - Pointers 65

Dynamic Memory Dynamic Memory is very powerful

C++ trusts you as the programmer to manage you own memory

While this gives you lots of control, it is easy to make mistakes.

Dynamic memory bugs are the most common of large software written in C++.

Page 66: Pointers (Chapter 9)

COMP103 - Pointers 66

The Dangling Pointer Bug

Be careful when you delete memory pointed to by p, you are not erasing a location that some other pointer q is pointing to.int *p, *q;P = new int;q = p;delete p;// q is a dangling pointer

p

qint

p

qint delete p

Page 67: Pointers (Chapter 9)

COMP103 - Pointers 67

Memory Leak Problem (bug)

Make sure to delete memory when finished

int *p;

p = new int[100];

int a;

NO ONE HAS ACCESS TO THIS MEMORYNO ONE HAS ACCESS TO THIS MEMORY 100 integersp = &a;

aa

100 integers

aa

This memory is un-addressableAnd it is reserved until yourprogram terminates

(it has leaked from the system)

Page 68: Pointers (Chapter 9)

COMP103 - Pointers 68

Dynamic Memory

Allows you to create “logical” structures by piecing together pointers + dynamic memory

For example, how could we build a 2D array using Dynamic Memory?

Page 69: Pointers (Chapter 9)

COMP103 - Pointers 69

A Dynamic 2D Array – An array of pointers

int **table;// a ragged array

Figure 9-41

(p.461)

Page 70: Pointers (Chapter 9)

COMP103 - Pointers 70

Allocation of 2D Array

int **data;int rows=3, cols=4;

data = new int*[ rows ];

Computer’s Memory

data = 102000

data[i] is a int * (points to int!) // allocate row’s data

for(int i=0; i < rows; i++){ data[i] = new int[cols];}

i=0data[i] = 008004

008004

008008

008012

008016

i=0

008004

009020

009024

009028

009032

i=1

009020

i=1data[i] = 009020

007392

007396

007400

007404

i=2

007392

i=2data[i] = 007392

// Initialize datafor(i=0; i < rows; i++) for(int j=0; j< cols; j++) { data[i][j] = 0; // or *(*(data+i)+j)=0 }

0000

0000

0000

102000

102004

102008

(array of int *)

Page 71: Pointers (Chapter 9)

COMP103 - Pointers 71

Deleting a 2D Array

Computer’s Memory

// delete row’s datafor(int i=0; i < rows; i++){ delete [ ] data[i];}

102000

102004

102008

delete memory atdata[0] = 008004

delete memory atdata[1] = 009020

delete memory atdata[2] = 007392

008004

008008

008012

008016

i=0

008004

0000

009020

009024

009028

009032

i=1

009020

0000

007392

007396

007400

007404

i=2

007392

0000D

ELET

ED

DEL

ETED

DEL

ETED

DEL

ETED

delete memory atdata = 102000

delete [ ] data;

Page 72: Pointers (Chapter 9)

COMP103 - Pointers 72

Using Dynamic Arrays

Figure 9-43

(p.465)

Page 73: Pointers (Chapter 9)

COMP103 - Pointers 73

Implementation of Dynamic Array

Figure 9-44

(p.465)

Complete examples Programs 9-15 to 9-23, pp. 466-470.

Page 74: Pointers (Chapter 9)

COMP103 - Pointers 74

Summary

Introduced Pointers and Dynamic Memory Pointers

are special variables that point to memory locations New declaration

int *p; char *p; int **p; char ***p; 2 new operators

p = &a; // address of a *p = 5; // Indirection operator *(p)

Page 75: Pointers (Chapter 9)

COMP103 - Pointers 75

Summary

Pointers relationship to arraysint a[10];int *p;

p = a; // a is really a pointer too!p = &a[1];

Passing pointers to functions Pointer Arithmetic

*(a+1) same as a[1] *(a+9) same as a[9]

Page 76: Pointers (Chapter 9)

COMP103 - Pointers 76

Summary Dynamic Memory

new and delete calls int *p = new int[100];

int *a = new int;

delete a;delete [] p;

Complex Uses for Dynamic Memory Example: Dynamic 2D array

int **table = new int*[3]; tables[0] = new int[10];tables[1] = new int[2];tables[2] = new int[100];

Page 77: Pointers (Chapter 9)

COMP103 - Pointers 77

Summary: Pointers and your sanity Pointers are very powerful

Allow you to directly access the computer’s memory

This freedom can cause problems

Remember Avoid Memory Leaks, Dangling Pointers Don’t access uninitialized pointers! Be kind to others!

int *bad_student = new int[1000000000000000];