1 chapter 9 pointers. 2 topics 8.1 getting the address of a variable 8.2 pointer variables 8.3...

30
1 Chapter 9 Pointers

Upload: sharyl-flynn

Post on 21-Dec-2015

247 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

1

Chapter 9

Pointers

Page 2: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

2

Topics

8.1 Getting the Address of a Variable

8.2 Pointer Variables

8.3 Relationship Between Arrays and Pointers

8.4 Pointer Arithmetic

8.5 Initializing Pointers

Page 3: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

3

Topics

8.6 Comparing Pointers

8.7 Pointers as Function Parameters

8.8 Dynamic Memory Allocation

8.9 Returning Pointers from Functions

Page 4: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

4

C++ Variables

A Variable has all of the following attributes:

1. name

2. type

3. size

4. value

5. storage class static or automatic

6. scope where it is known in the program

7. linkage use of extern and static qualifiers

8. address the address in memory of the variable

Page 5: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

5

8.1 Getting the Address of a Variable

Each variable in a program is stored at a unique address

Use address operator & to get the address of a variable:

int num = -23;cout << &num; // prints address

// in hexadecimal

Page 6: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

6

8.2 Pointer Variables

Pointer variable (pointer): • variable that holds an address

Can perform some tasks more easily with an address than by accessing memory via a symbolic name:

• Accessing unnamed memory locations• Array manipulation• etc.

Page 7: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

7

Pointer Variables Definition:

int *intPtr; // can hold the address of an int

Read as:

intPtr is a pointer to an integer

Spacing in definition does not matter:

int *intPtr; // same as aboveint* intPtr; // same as above

Page 8: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

8

Chapter 8 – Pointers

char

int

double

Page 9: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

9

Pointer Variables

Assignment:

int *intPtr;intPtr = &num;

Memory layout:

You access num using intPtr and the indirection operator ( * )

cout << *intPtr << endl; // prints 25

//the indirection operator dereferences a variable

num intPtr25 0x4a00

address of num: 0x4a00

Page 10: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

10

8.3 The Relationship Between Arrays and Pointers

An array name is a constant pointer to the first element in an array. It holds an address.

int vals[] = {4, 7, 11};

cout << vals; // displays 0x4a00

cout << vals[0]; // displays 4

4 7 11starting address of vals: 0x4a00

Page 11: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

11

The Relationship Between Arrays and Pointers

An array name can be used as a pointer constant:int vals[] = {4, 7, 11};

cout << *vals; // displays 4

A Pointer can be used as an array name:int *valPtr = vals;

cout << valPtr[1]; //displays 7

cout << *(valPtr+1); //displays 7

cout << valPtr; //displays address of vals

Page 12: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

12

Pointers in Expressions

Given:

int vals[] = {4,7,11}, *valPtr;valPtr = vals;

What is valPtr + 1 ? It means (address in valptr) + (1 * size of an int)

cout << *(valPtr+1); //displays 7cout << *(valPtr+2); //displays 11

Must use ( ) in expression

Page 13: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

13

Array Access

Array elements can be accessed in many ways:

Use of [ ] subscript and * offset notation

Array access method Example

array name and [] vals[2] = 17;

pointer to array and [] valPtr[2] = 17;

array name and pointer arithmetic

*(vals + 2) = 17;

pointer to array and pointer arithmetic

*(valPtr + 2) = 17;

Page 14: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

14

Array Access

Conversion:

•vals[i] is equivalent to *(vals + i)

No bounds checking performed on array access, whether using array name or a pointer

Page 15: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

15

8.4 Pointer Arithmetic

Operation Exampleint vals[] = {4,7,11}; int *valPtr = vals;

++, -- valPtr++; // points at 7valPtr--; // now points at 4

+, - (pointer and int) cout << *(valPtr + 2); // 11

+=, -= (pointer and int) valPtr = vals; // points at 4valPtr += 2; // points at 11

- (pointer from pointer) cout << valPtr – val; // difference//(number of ints) between valPtr// and val

Page 16: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

16

8.5 Initializing Pointers Can initialize at definition time:

int num, *numPtr = &num;int val[3], *valPtr = val;

int *ptr = 0; //create a pointer initialized to 0 //ptr is currently a NULL pointer

Cannot mix data types:

double cost;int *ptr = &cost; // won’t work

Can test for an invalid address for ptr with:

if (!ptr) …

Page 17: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

17

8.6 Comparing Pointers

Relational operators can be used to compare addresses in pointers

Comparing addresses in pointers is not the same as comparing the values pointed at by pointers:

if (ptr1 == ptr2) // compares // addresses

if (*ptr1 == *ptr2) // compares // values

Page 18: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

18

8.7 Pointers as Function Parameters

A pointer can be parameter

Works like reference variable to allow change to argument from within function

Requires:

1) asterisk * on parameter in prototype and heading

void getNum(int *ptr); // ptr is pointer to an int

2) asterisk * in body to dereference the pointercin >> *ptr;

3) address as argument to the functiongetNum(&num); // pass address of num to getNum

Page 19: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

19

Pointers as Function Parameters

void swap(int *x, int *y){ int temp;

temp = *x;*x = *y;*y = temp;

}

int num1 = 2, num2 = -3;swap(&num1, &num2);

Page 20: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

20

8.7 Pointers as Function Parameters A pointer can be used as a function parameter. It

gives the function access to the original argument, much like a reference parameter does.

void double ( int &); // reference void double ( int * ); // pointer

a reference is a "constant" pointer

Page 21: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

21

Keyword const with pointers/data( not in book! )

[ const ] <type> * [ const ] <variable>

constant data constant pointer

int x = 100;

const int * const xPtr = &x;

// xPtr is a constant pointer to an integer constant

Page 22: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

22

Creating a constant pointer

The const qualifier is used by a programmer to inform the compiler that the value of a particular variable should not be modified.

• The const qualifier can be applied to a pointer making it a constant pointer.

• int x = 100, y = 10;

• int * const intPtr = &x; // defines intPtr as a constant pointer to an integer

• intPtr = &y; // error! intPtr is a constant pointer

• *intPtr += 100; // x now contains 200 (constant pointer, not data)

• A constant pointer cannot be assigned a new address

Page 23: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

23

Creating a pointer to constant data

A pointer can be declared to point to a constant type. In this situation the pointer can be assigned a new address but the data in the object it points to cannot be modified.

int x = 100, y = 10;

const int * intPtr = &x; // intPtr is a pointer to an integer constant

intPtr = &y; // intPtr now points to y

*intPtr += 100; // error! Cannot change constant data

A constant variable cannot be updated through a dereferenced pointer.

Page 24: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

24

8.8 Dynamic Memory Allocation

A program can allocate storage for a variable while it is running

Use the new operator to allocate memory:double *dblPtr;

dblPtr = new double;

new returns the address of a memory location if it is successful or 0 ( NULL ) if not.

Page 25: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

25

Dynamic Memory Allocation

You can use new to dynamically allocate an array:

double *arrayPtr;cout << "How many real numbers? ";cin >> count;arrayPtr = new double[count];//count is a variable!

You can use subscript or offset notation to access the array elements.

for (int i = 0; i < count; i++) arrayptr[i] = i * i;

or for (int i = 0; i < count; i++)

*(arrayptr + i) = i * i;

Page 26: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

26

Releasing Dynamic Memory

Use delete to free dynamic memory:delete fPtr; //single element

Use [] to free a dynamic array:delete [] arrayPtr; //array of elements

Only use delete with dynamically allocated memory!

Page 27: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

27

8.9 Returning Pointers from Functions

A pointer can be the return type of function:

int* newNum();

Function must not return a pointer to an automatic local variable in the function

Function should only return a pointer:

• to data that was passed to the function as an argument

• to dynamically allocated memory

Page 28: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

28

8.9 Returning Pointers from Functions

char *getName( )

{

char name[81];

cout<<"Enter your name: ";

cin.getline(name, 81);

return name; //not allowed

}

char *getName(char *name)

{

cout<<"Enter your name: ";

cin.getline(name, 81);

return name;

}

char *getName( )

{

char *name;

name = new char[81];

cout<<"Enter your name: ";

cin.getline(name, 81);

return name;

}

Page 29: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

29

A Final array example#include <iostream>using namespace std;int main(){

int sales[3][4] = { {100,500,200,250}, {300,250,400,500}, {450,350,400,200} };

cout << "The sales array is defined as: int sales[3][4]" << endl << endl;cout << "The value of sales is: " << sales << endl;

for (int j =0; j<3; j++)cout << "The value of sales[" << j << "] is: " << sales[j] << endl;

cout << endl;

for (int m=0; m<3; m++) for (int n=0; n<4; n++)

cout << sales[m][n] << " ";cout << endl;

for (m=0; m<3; m++) for (int n=0; n<4; n++)

cout << *(*(sales+m)+n) << " "; // array name – offset notation for acout << endl << endl; // two-dimensional arrayreturn 0;

}

*(*(*(*(name + d1)+d2)+d3)+d4)… // equivalent to name[d1][d2][d3][d4]… name is the name of the array or pointer d1, d2, d3 … represent values used for the different dimensions in a multi-dimensional array

Page 30: 1 Chapter 9 Pointers. 2 Topics 8.1 Getting the Address of a Variable 8.2 Pointer Variables 8.3 Relationship Between Arrays and Pointers 8.4 Pointer Arithmetic

30

The sales array is defined as: int sales[3][4]

The value of sales is: 0x0012FF50The value of sales[0] is: 0x0012FF50The value of sales[1] is: 0x0012FF60The value of sales[2] is: 0x0012FF70

100 500 200 250 300 250 400 500 450 350 400 200100 500 200 250 300 250 400 500 450 350 400 200