pointers and dynamic memory allocation. declaring a pointer

71
Pointers and Dynamic Memory Allocation

Upload: arline-summers

Post on 04-Jan-2016

239 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Pointers and Dynamic Memory Allocation. Declaring a pointer

Pointers and Dynamic Memory Allocation

Page 2: Pointers and Dynamic Memory Allocation. Declaring a pointer

Declaring a pointer

Page 3: Pointers and Dynamic Memory Allocation. Declaring a pointer

Declaring a pointer

• int* p;• or• int *p;• string* q;• pointer operations• &- Address of operator• *- Contents of operator

Page 4: Pointers and Dynamic Memory Allocation. Declaring a pointer

Using the & operator

Page 5: Pointers and Dynamic Memory Allocation. Declaring a pointer
Page 6: Pointers and Dynamic Memory Allocation. Declaring a pointer

• X=25 • X= 30 • X= 35• X=40

Page 7: Pointers and Dynamic Memory Allocation. Declaring a pointer
Page 8: Pointers and Dynamic Memory Allocation. Declaring a pointer

Pointers

• Pointers– Powerful feature of the C++ language– One of the most difficult to master– Essential for construction of interesting data

structures

8

Page 9: Pointers and Dynamic Memory Allocation. Declaring a pointer

Addresses and Pointers

• C++ allows two ways of accessing variables– Name (C++ keeps track of the address of the first

location allocated to the variable)– Address/Pointer

• Symbol & gets the address of the variable that follows it

• Addresses/Pointers can be displayed by the cout statement– Addresses displayed in HEXADECIMAL

9

Page 10: Pointers and Dynamic Memory Allocation. Declaring a pointer

Example

#include <iostream.h>main( ){ int data = 100; float value = 56.47; cout << data << &data << endl; cout << value << &value << endl;System(“pause”);}

Output:

100 FFF456.47 FFF0

10

56.47

100

FFF1

FFF0

FFF2

FFF3

FFF4

FFF5

FFF6

value

data

Page 11: Pointers and Dynamic Memory Allocation. Declaring a pointer

Pointer Variables

• The pointer data type– A data type for containing an address rather than

a data value– Integral, similar to int– Size is the number of bytes in which the target

computer stores a memory address– Provides indirect access to values

11

Page 12: Pointers and Dynamic Memory Allocation. Declaring a pointer

Declaration of Pointer Variables

• A pointer variable is declared by: dataType *pointerVarName;– The pointer variable pointerVarName is used to

point to a value of type dataType– The * before the pointerVarName indicates that

this is a pointer variable, not a regular variable– The * is not a part of the pointer variable name

12

Page 13: Pointers and Dynamic Memory Allocation. Declaring a pointer

Declaration of Pointer Variables (Cont ..)

• Example int *ptr1; float *ptr2;– ptr1 is a pointer to an int value i.e., it can have

the address of the memory location (or the first of more than one memory locations) allocated to an int value

– ptr2 is a pointer to a float value i.e., it can have the address of the memory location (or the first of more than one memory locations) allocated to a float value

13

Page 14: Pointers and Dynamic Memory Allocation. Declaring a pointer

Declaration of Pointer Variables (Cont ..)

• Whitespace doesn’t matter and each of the following will declare ptr as a pointer (to a float) variable and data as a float variable

float *ptr, data; float* ptr, data; float (*ptr), data; float data, *ptr;

14

Page 15: Pointers and Dynamic Memory Allocation. Declaring a pointer

Assignment of Pointer Variables

A pointer variable has to be assigned a valid memory address before it can be used in the program

Example: float data = 50.8; float *ptr; ptr = &data;

This will assign the address of the memory location allocated for the floating point variable data to the pointer variable ptr. This is OK, since the variable data has already been allocated some memory space having a valid address

15

Page 16: Pointers and Dynamic Memory Allocation. Declaring a pointer

Assignment of Pointer Variables (Cont ..)

16

float data = 50.8;

float *ptr;

ptr = &data; 50.8

FFF1

FFF0

FFF2

FFF3

FFF4

FFF5

FFF6

data

Page 17: Pointers and Dynamic Memory Allocation. Declaring a pointer

Assignment of Pointer Variables (Cont ..)

17

float data = 50.8;

float *ptr;

ptr = &data; 50.8

FFF1

FFF0

FFF2

FFF3

FFF4

FFF5

FFF6

ptr

data

Page 18: Pointers and Dynamic Memory Allocation. Declaring a pointer

Assignment of Pointer Variables (Cont ..)

18

float data = 50.8;

float *ptr;

ptr = &data;

FFF4

50.8

FFF1

FFF0

FFF2

FFF3

FFF4

FFF5

FFF6

ptr

data

Page 19: Pointers and Dynamic Memory Allocation. Declaring a pointer

Assignment of Pointer Variables (Cont ..)

• Don’t try to assign a specific integer value to a pointer variable since it can be disastrous float *ptr; ptr = 120;

19

• You cannot assign the address of one type of variable to a pointer variable of another type even though they are both integrals

int data = 50; float *ptr; ptr = &data;

Page 20: Pointers and Dynamic Memory Allocation. Declaring a pointer

Initializing pointers

• A pointer can be initialized during declaration by assigning it the address of an existing variable

float data = 50.8; float *ptr = &data;

• If a pointer is not initialized during declaration, it is wise to give it a NULL (0) value int *ip = 0; float *fp = NULL;

20

Page 21: Pointers and Dynamic Memory Allocation. Declaring a pointer

The NULL pointer

• The NULL pointer is a valid address for any data type.– But NULL is not memory address 0.

• It is an error to dereference a pointer whose value is NULL.– Such an error may cause your program to crash,

or behave erratically.– It is the programmer’s job to check for this.

21

Page 22: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dereferencing

• Dereferencing – Using a pointer variable to access the value stored at the location pointed by the variable– Provide indirect access to values and also

called indirection• Done by using the dereferencing operator *

in front of a pointer variable– Unary operator– Highest precedence

22

Page 23: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dereferencing (Cont ..)

• Example: float data = 50.8; float *ptr; ptr = &data; cout << *ptr;

• Once the pointer variable ptr has been declared, *ptr represents the value pointed to by ptr (or the value located at the address specified by ptr) and may be treated like any other variable of float type

23

Page 24: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dereferencing (Cont ..)

• The dereferencing operator * can also be used in assignments.

*ptr = 200;– Make sure that ptr has been properly initialized

24

Page 25: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dereferencing Example

25

#include <iostream.h>

void main(){ float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl;system("pause");}

Output:

FFF4

50.8

FFF1

FFF0

FFF2

FFF3

FFF4

FFF5

FFF6

ptr

data

Page 26: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dereferencing Example (Cont ..)

26

#include <iostream.h>

void main(){ float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl;}

Output:

FFF4 50.80

FFF4

50.8

FFF1

FFF0

FFF2

FFF3

FFF4

FFF5

FFF6

ptr

data

Page 27: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dereferencing Example (Cont ..)

27

FFF4

27.4

FFF1

FFF0

FFF2

FFF3

FFF4

FFF5

FFF6

ptr

data

#include <iostream.h>

void main(){ float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl;}

Output:

Page 28: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dereferencing Example (Cont ..)

28

FFF4

27.4

FFF1

FFF0

FFF2

FFF3

FFF4

FFF5

FFF6

ptr

data

#include <iostream.h>

void main(){ float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl;}

Output:

27.4

Page 29: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dereferencing Example (Cont ..)

29

FFF4

27.4

FFF1

FFF0

FFF2

FFF3

FFF4

FFF5

FFF6

ptr

data

#include <iostream.h>

void main(){ float data = 50.8; float *ptr; ptr = &data; cout << ptr << *ptr << endl; *ptr = 27.4; cout << *ptr << endl; cout << data << endl;}

Output:

27.4

Page 30: Pointers and Dynamic Memory Allocation. Declaring a pointer

Operations on Pointer Variables

• Assignment – the value of one pointer variable can be assigned to another pointer variable of the same type

• Relational operations - two pointer variables of the same type can be compared for equality, and so on

• Some limited arithmetic operations – integer values can be added to and subtracted

from a pointer variable– value of one pointer variable can be subtracted

from another pointer variable

30

Page 31: Pointers and Dynamic Memory Allocation. Declaring a pointer

Pointers to arrays

• A pointer variable can be used to access the elements of an array of the same type.

• #include <iostream.h>

main(){ int gradeList[8] = {92,85,75,88,79,54,34,96}; int *myGrades = gradeList; cout << gradeList[1]<<"\t"; cout << *myGrades<<"\t"; cout << *(myGrades + 2)<<"\t"; cout << myGrades[3]<<"\t"; system("pause");}

Note that the array name gradeList acts like the pointer variable myGrades.

31

Page 32: Pointers and Dynamic Memory Allocation. Declaring a pointer

32

Dynamic Memory Allocation

Page 33: Pointers and Dynamic Memory Allocation. Declaring a pointer

Types of Program Data

• Static Data: Memory allocation exists throughout execution of program

• Automatic Data: Automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function

• Dynamic Data: Explicitly allocated and deallocated during program execution by C++ instructions written by programmer

33

Page 34: Pointers and Dynamic Memory Allocation. Declaring a pointer

Allocation of Memory

• Static Allocation: Allocation of memory space at compile time.

• Dynamic Allocation: Allocation of memory space at run time.

34

Page 35: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dynamic memory allocation

• Dynamic allocation is useful when– arrays need to be created whose extent is not

known until run time– complex structures of unknown size and/or shape

need to be constructed as the program runs– objects need to be created and the constructor

arguments are not known until run time

35

Page 36: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dynamic memory allocation

• Pointers need to be used for dynamic allocation of memory

• Use the operator new to dynamically allocate space

• Use the operator delete to later free this space

36

Page 37: Pointers and Dynamic Memory Allocation. Declaring a pointer

The new operator

• If memory is available, the new operator allocates memory space for the requested object/array, and returns a pointer to (address of) the memory allocated.

• If sufficient memory is not available, the new operator returns NULL.

• The dynamically allocated object/array exists until the delete operator destroys it.

37

Page 38: Pointers and Dynamic Memory Allocation. Declaring a pointer

The delete operator

• The delete operator deallocates the object or array currently pointed to by the pointer which was previously allocated at run-time by the new operator.– the freed memory space is returned to Heap– the pointer is then considered unassigned

• If the value of the pointer is NULL there is no effect.

38

Page 39: Pointers and Dynamic Memory Allocation. Declaring a pointer

Example

39

FDE1

FDE0

0EC7

FDE2

FDE3

0EC4

0EC5

0EC6

ptrint *ptr;

ptr = new int;

*ptr = 22;

cout << *ptr << endl;

delete ptr;

ptr = NULL;

Page 40: Pointers and Dynamic Memory Allocation. Declaring a pointer

40

Example (Cont ..)

int *ptr;

ptr = new int;

*ptr = 22;

cout << *ptr << endl;

delete ptr;

ptr = NULL;

0EC4

FDE1

FDE0

0EC7

FDE2

FDE3

0EC4

0EC5

0EC6

ptr

Page 41: Pointers and Dynamic Memory Allocation. Declaring a pointer

41

Example (Cont ..)

int *ptr;

ptr = new int;

*ptr = 22;

cout << *ptr << endl;

delete ptr;

ptr = NULL;

0EC4

22

FDE1

FDE0

0EC7

FDE2

FDE3

0EC4

0EC5

0EC6

ptr

Page 42: Pointers and Dynamic Memory Allocation. Declaring a pointer

42

Example (Cont ..)

int *ptr;

ptr = new int;

*ptr = 22;

cout << *ptr << endl;

delete ptr;

ptr = NULL;

?

FDE1

FDE0

0EC7

FDE2

FDE3

0EC4

0EC5

0EC6

ptr

Page 43: Pointers and Dynamic Memory Allocation. Declaring a pointer

43

Example (Cont ..)

int *ptr;

ptr = new int;

*ptr = 22;

cout << *ptr << endl;

delete ptr;

ptr = NULL;

0

FDE1

FDE0

0EC7

FDE2

FDE3

0EC4

0EC5

0EC6

ptr

Page 44: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dynamic allocation and deallocation of arrays

• Use the [IntExp] on the new statement to create an array of objects instead of a single instance.

• On the delete statement use [] to indicate that an array of objects is to be deallocated.

44

Page 45: Pointers and Dynamic Memory Allocation. Declaring a pointer

Example of dynamic array allocation

45

#include <iostream.h> main(){int* grades = NULL;int numberOfGrades;

cout << "Enter the number of grades: ";cin >> numberOfGrades;grades = new int[numberOfGrades];

for (int i = 0; i < numberOfGrades; i++) cin >> grades[i];

for (int j = 0; j < numberOfGrades; j++) cout << grades[j] << " ";

delete [] grades;grades = NULL;system("pause");}

Page 46: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dynamic allocation of 2D arrays

• A two dimensional array is really an array of arrays (rows).

• To dynamically declare a two dimensional array of int type, you need to declare a pointer to a pointer as: int **matrix;

46

Page 47: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dynamic allocation of 2D arrays (Cont ..)

To allocate space for the 2D array with r rows and c columns:You first allocate the array of pointers which will

point to the arrays (rows) matrix = new int*[r];

This creates space for r addresses; each being a pointer to an int.

Then you need to allocate the space for the 1D arrays themselves, each with a size of c

for(i=0; i<r; i++) matrix[i] = new int[c];

47

Page 48: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dynamic allocation of 2D arrays (Cont ..)

• The elements of the array matrix now can be accessed by the matrix[i][j] notation

• Keep in mind, the entire array is not in contiguous space (unlike a static 2D array)

• The elements of each row are in contiguous space, but the rows themselves are not.– matrix[i][j+1] is after matrix[i][j] in

memory, but matrix[i][0] may be before or after matrix[i+1][0] in memory

48

Page 49: Pointers and Dynamic Memory Allocation. Declaring a pointer

Example

// create a 2D array dynamicallyint rows, columns, i, j;int **matrix;cin >> rows >> columns;matrix = new int*[rows];for(i=0; i<rows; i++) matrix[i] = new int[columns];

49

// deallocate the arrayfor(i=0; i<rows; i++) delete [] matrix[i];delete [] matrix;

Page 50: Pointers and Dynamic Memory Allocation. Declaring a pointer

50

Passing pointers to a function

Page 51: Pointers and Dynamic Memory Allocation. Declaring a pointer

Pointers as arguments to functions

• Pointers can be passed to functions just like other types.

• Just as with any other argument, verify that the number and type of arguments in function invocation match the prototype (and function header).

51

Page 52: Pointers and Dynamic Memory Allocation. Declaring a pointer

Example of pointer arguments

void Swap(int *p1, int *p2);

void main (){ int x, y; cin >> x >> y; cout << x << " " << y << endl; Swap(&x,&y); // passes addresses of x and y explicitly cout << x << " " << y << endl;}

void Swap(int *p1, int *p2){ int temp = *p1; *p1 = *p2; *p2 = temp;}

52

Page 53: Pointers and Dynamic Memory Allocation. Declaring a pointer

Example of reference argumentsvoid Swap(int &a, int &b);

void main (){ int x, y; cin >> x >> y; cout << x << " " << y << endl; Swap(x,y); // passes addresses of x and y implicitly cout << x << " " << y << endl;}

void Swap(int &a, int &b){ int temp = a; a = b; b = temp;}

53

Page 54: Pointers and Dynamic Memory Allocation. Declaring a pointer

More example

54

void main (){ int r, s = 5, t = 6; int *tp = &t; r = MyFunction(tp,s); r = MyFunction(&t,s); r = MyFunction(&s,*tp);}

int MyFunction(int *p, int i){ *p = 3; i = 4; return i;}

Page 55: Pointers and Dynamic Memory Allocation. Declaring a pointer

55

Memory leaks andDangling Pointers

Page 56: Pointers and Dynamic Memory Allocation. Declaring a pointer

Memory leaks

• When you dynamically create objects, you can access them through the pointer which is assigned by the new operator

• Reassigning a pointer without deleting the memory it pointed to previously is called a memory leak

• It results in loss of available memory space

56

Page 57: Pointers and Dynamic Memory Allocation. Declaring a pointer

Memory leak example

57

int *ptr1 = new int;int *ptr2 = new int;*ptr1 = 8;*ptr2 = 5;

ptr1

8

5

ptr2

ptr1

8

5

ptr2

ptr2 = ptr1;

How to avoid?How to avoid?

Page 58: Pointers and Dynamic Memory Allocation. Declaring a pointer

Inaccessible object

• An inaccessible object is an unnamed object that was created by operator new and which a programmer has left without a pointer to it.

• It is a logical error and causes memory leaks.

58

Page 59: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dangling Pointer

• It is a pointer that points to dynamic memory that has been deallocated.

• The result of dereferencing a dangling pointer is unpredictable.

CSC2110 - Data Structures/Algorithms 59

Page 60: Pointers and Dynamic Memory Allocation. Declaring a pointer

60

Dangling Pointer example

int *ptr1 = new int;int *ptr2;*ptr1 = 8;ptr2 = ptr1;

ptr1

8

ptr2

delete ptr1;

ptr1

ptr2How to avoid?How to avoid?

Page 61: Pointers and Dynamic Memory Allocation. Declaring a pointer

Pointers to objects

Page 62: Pointers and Dynamic Memory Allocation. Declaring a pointer

Pointers to objects

• Any type that can be used to declare a variable/object can also have a pointer type.

• Consider the following class:

62

class Rational{ private: int numerator; int denominator; public: Rational(int n, int d); void Display();};

Page 63: Pointers and Dynamic Memory Allocation. Declaring a pointer

Pointers to objects (Cont..)

63

Rational *rp = NULL;Rational r(3,4);rp = &r;

0FFF0FFF1FFF2FFF3FFF4FFF5FFF6FFF7FFF8FFF9FFFAFFFBFFFCFFFD

rp

Page 64: Pointers and Dynamic Memory Allocation. Declaring a pointer

Pointers to objects (Cont..)

64

Rational *rp = NULL;Rational r(3,4);rp = &r;

0FFF0

numerator = 3denominator =

4

FFF1FFF2FFF3

3FFF4FFF5FFF6FFF7

4FFF8FFF9FFFAFFFBFFFCFFFD

rp

r

Page 65: Pointers and Dynamic Memory Allocation. Declaring a pointer

Pointers to objects (Cont..)

65

Rational *rp = NULL;Rational r(3,4);rp = &r;

FFF4FFF0

numerator = 3denominator =

4

FFF1FFF2FFF3

3FFF4FFF5FFF6FFF7

4FFF8FFF9FFFAFFFBFFFCFFFD

r

rp

Page 66: Pointers and Dynamic Memory Allocation. Declaring a pointer

Pointers to objects (Cont..)

• If rp is a pointer to an object, then two notations can be used to reference the instance/object rp points to.

• Using the de-referencing operator * (*rp).Display();

• Using the member access operator -> rp -> Display();

66

Page 67: Pointers and Dynamic Memory Allocation. Declaring a pointer

Dynamic Allocation of a Class Object

• Consider the Rational class defined before

Rational *rp;int a, b;cin >> a >> b;rp = new Rational(a,b);(*rp).Display(); // rp->Display();delete rp;rp = NULL;

67

Page 68: Pointers and Dynamic Memory Allocation. Declaring a pointer

• return 0;• }*/

• // using the & and * operators• #include<iostream.h>• main ( )• {• int a ; //a is an integer• int *aptr; // aptr is apointer to an integer• a = 7;• aptr = &a; // aptr set to address of a• cout <<" The address of a is " << &a <<endl• << "The value of aptr is " << aptr<< endl<< endl;

• cout << "The value of a is " << a<< endl• << "The value of *aptr is " << *aptr<< endl<<endl;• cout<<" Proving that * and & are complement of "• << "each other." <<endl<< " & *ptr = "<< & *aptr• << endl<< " *&aptr = " << *&aptr <<endl;• system("pause");• return 0;

Page 69: Pointers and Dynamic Memory Allocation. Declaring a pointer
Page 70: Pointers and Dynamic Memory Allocation. Declaring a pointer
Page 71: Pointers and Dynamic Memory Allocation. Declaring a pointer