31
1 Writing a Good Program 6. Pointers and Arrays

Writing a Good Program 6. Pointers and Arrays

Embed Size (px)

DESCRIPTION

Writing a Good Program 6. Pointers and Arrays. Computer Programming and Basic Software Engineering. 6. Pointers and Arrays. 6.1 Pointers. Computer Programming and Basic Software Engineering. 6. Pointers and Arrays. How memory is used in C++?. - PowerPoint PPT Presentation

Citation preview

1

Writing a Good Program 6. Pointers and Arrays

2

6.1 Pointers

Computer Programming and Basic Software Engineering6. Pointers and Arrays

3

How memory is used in C++?• The whole big piece of memory is divided into 4

areas:

Code Space - for the storage of program code

Stack - for the storage of local variables, passed parameters.

Global Name Space - for the storage of global variables

Free storeFree store - for the storage of dynamically created data

Computer Programming and Basic Software Engineering6. Pointers and Arrays

4

Free Storeor

the heap

Global Name SpaceCode SpaceThe Stack

How memory is used in C++?

Computer Programming and Basic Software Engineering6. Pointers and Arrays

funcB(){ Cat Frisky; return;}

funcA(){ int a; return;}

main(){ Statements; funcA(); Statements; funcB(); Statements;}

5

• A variable is a storage space in memory.

• Every variable has a memory address.

What is the Address of a Variable?

0100 0101 0102 0103 0104 0105 0106 0107 0108 0109Address

Memory

Variables char a int b short int c bool d

30 0A 21 3A 51 44 20 00

a = 30 Address of a = 0100

b = 0A 21 3A 51 Address of b = 0101

c = 44 20 Address of c = 0105

Computer Programming and Basic Software Engineering6. Pointers and Arrays

All values written in hexadecimal but binary in reality

The character '0'

Each byte has an addressEach variable has the starting-byte address

6

• In C++, the symbol & is used to indicate the address of a variable. #include <iostream>

using namespace std;int main(){ unsigned short shortVar = 5;

unsigned long longVar = 65535;long sVar = -65535;cout << "shortVar:\t" << shortVar;cout << "\tAddress of shortVar:\t";cout << &shortVar << "\n";cout << "longVar:\t" << longVar;cout << "\tAddress of longVar:\t";cout << &longVar << "\n";cout << "sVar:\t\t" << sVar;cout << "\tAddress of sVar:\t";cout << &sVar << "\n";return 0;

}

The addresses of shortVar, longVar and

sVar

The addresses of shortVar, longVar and

sVar

What is the Address of a Variable?

Computer Programming and Basic Software Engineering6. Pointers and Arrays

7

• Variable and address of a variable are different.

What is the Address of a Variable?

Computer Programming and Basic Software Engineering6. Pointers and Arrays

8 Computer Programming and Basic Software Engineering6. Pointers and Arrays

What is a Pointer?

• In many situations, we want to store the address of a variable into a particular memory location.

0100 0101 0102 0103 0104 0105 0106 0107 0108 0109Address

Memory

Variables char a int b (address of a) pa

10 0A 21 3A 51 00 0100 00

• pa is a variable that can store the address of a.

• In C++, every address has 4 bytes. So we need to reserve 4 bytes of memory to store the address of a .

pa is the pointer of a

9 Computer Programming and Basic Software Engineering6. Pointers and Arrays

What is a Pointer?

• In C++, every variable needs to have its type declared.

int abc; // means abc belongs to the type of integer.

CAT Felix; // means Felix belongs to the class CAT

• If we want to declare the type of pa, which stores the address of a variable a, how should we do it?

How about address pa;

Not good enough, since it does not tell the nature of a Not good enough, since it does not tell the nature of a

How about (address of a character) pa;

Better, but look too clumsy Better, but look too clumsy

10 Computer Programming and Basic Software Engineering6. Pointers and Arrays

What is a Pointer?• C++ uses an elegant way to solve the problem (but need some

time to understand!).

• It introduces a symbol *.

means the content of an address.

0100 0101 0102 0103 0104 0105 0106 0107 0108 0109Address

Memory

Variables char a int b char *pa

10 0A 21 3A 51 00 0100 00

• char *pa indicates that the memory content of the address. stored in pa is a character. pa is indirectly declared to be an address of character.

pa's content is an address, the memory content of that address is a character

11

What is a Pointer?

char *pa, a=0x30; // 48cout << a; // a = '0'pa = &a; // pa = 0100cout << *pa; // *pa = 30*pa = 49; // a = '1'cout << a;

Computer Programming and Basic Software Engineering6. Pointers and Arrays

0100 0101 0102 0103 0104 0105 0106 0107 0108 0109Address

Memory

Variables char a int b char *pa

30 0A 21 3A 51 00 0100 00

• We can modify the content of a memory location using pointer.

We modify a indirectly by using its address

We modify a indirectly by using its address

12 Computer Programming and Basic Software Engineering6. Pointers and Arrays#include <iostream>

using namespace std;typedef unsigned short int USHORT;int main(){ USHORT myAge; // a variable

USHORT * pAge = 0;// a null pointer, pAge=0, not *pAge=0// Don’t let it become wild pointer (point to unknown)myAge = 5;cout << "myAge: " << myAge << "\n";pAge = &myAge; // assign address of myAge to pAgecout << "*pAge: " << *pAge << "\n\n";cout << "*pAge = 7\n";*pAge = 7; // *pAge=7, not pAge=7, sets myAge to 7cout << "*pAge: " << *pAge << "\n";cout << "myAge: " << myAge << "\n\n";cout << "myAge = 9\n";myAge = 9;cout << "myAge: " << myAge << "\n";cout << "*pAge: " << *pAge << "\n";return 0;

}

13 Computer Programming and Basic Software Engineering6. Pointers and Arrays

14

Why Pointer? - Using Free Store• Pointer allows us to handle the memory in Free Store.

• The memory Free Store is opened to all functions.

• Pointer helps us to identify the part of memory in Free Store that is being used by a particular function or object.

• To use the memory in Free Store:

1. Make a claim to the system how much memory is required.

2. System allocates a memory space with big enough size.

3. System returns a pointer value which is the starting address of that memory space.

4. When the memory space is not required, release it back to the system for other functions.

Computer Programming and Basic Software Engineering6. Pointers and Arrays

15

new and delete

unsigned short int * pPointer;pPointer = new unsigned short int;:// after using the memory space:delete pPointer; // return it to system

Claim a piece of memory in Free Store with size that is equal to an unsigned short

integer.

Claim a piece of memory in Free Store with size that is equal to an unsigned short

integer.

The keywords new and delete help us claim and release memory in Free Store.

int * pPointer2;pPointer2 = new int[2];:// after using the memory space:delete [] pPointer2; // return it to system

We claim memory with size equals to 2 integers.

pPointer2 now points to the starting address of this

memory space.

We claim memory with size equals to 2 integers.

pPointer2 now points to the starting address of this

memory space.

Computer Programming and Basic Software Engineering6. Pointers and Arrays

Results unpredictable is no []Results unpredictable is no []

16

8003 8004 8005 8006 8007 8008 8009 800A 800B 800CAddress

Memory

Free Store

int * pPointer;unsigned short int * pPointer2;pPointer = new int;:pPointer2 = new unsigned short int [2];:delete pPointer; // return it to system delete [] pPointer2; // return it to system

pPointer = 8004pPointer = 8004

pPointer2 = 8008pPointer2 = 8008

Computer Programming and Basic Software Engineering6. Pointers and Arrays

17

Exercise 6.1The program on the next page will introduce the problem of memory leaks (the system cannot get back the memory allocated to the program) and execution error. Build the program and step over each line of code using the Run-time Debugger. Answer the following questions:

Computer Programming and Basic Software Engineering6. Pointers and Arrays

1. What is the address of localVariable?2. What is the value of pHeap after executing line 6?3. What is the value of pHeap after executing line 11?4. Assume that you can finish executing the program. Do

you think you can free the memory claimed by the new statement in line 6? If no, why not?

Modify the program such that we can free the memories claimed by both new statements in line 6 and line 11.

18

#include <iostream>using namespace std;int main(){ int localVariable = 5;

int * pLocal = &localVariable;int * pHeap = new int; //line 6*pHeap = 7;cout << "localVariable: " << localVariable << "\n";cout << "*pLocal: " << *pLocal << "\n";cout << "*pHeap: " << *pHeap << "\n";pHeap = new int; //line 11*pHeap = 9;cout << "*pHeap: " << *pHeap << "\n";delete pHeap;delete pHeap;return 0;

}

Computer Programming and Basic Software Engineering6. Pointers and Arrays

19

Stray (Wild or Dangling) Pointers• When one deletes a pointer, the associated memory will be

given back to system.

• If one tries to use that pointer again without reassigning it, the result is unpredictable.

• To ensure one will not use the deleted pointer again, always assign the pointer with the value 0 after delete.

• A stray (or wild, dangling) pointer is the pointer that has been deleted but without assigning to null.

int *pNum = new int(5); // Initialize *pNum to 5

delete pNum;

pNum = 0; // To ensure the program will crash rather

// than unpredictable if one reuses it

Computer Programming and Basic Software Engineering6. Pointers and Arrays

NULL points to ROM

delete a pointer ≠ remove a pointer, it still exists

20

Creating Objects in the Free Store• Similar to integer, we

can create objects in the Free Store.Cat *pCat = new Cat;

Free Storeor

the heap

Global Name SpaceCode SpaceThe Stack

Size enough for a Cat

pCat• pCat stores the

beginning address of the memory allocated.

• When the object is created, its constructor is called.

Computer Programming and Basic Software Engineering6. Pointers and Arrays

Object identified by a pointer.

21

Deleting Objects• Objects in the Free Store can also be deleted.

Cat *pCat = new Cat;

delete pCat;

• pCat becomes an identifier of the object created.

• When an object is deleted, its destructor will be called.

• Hence the destructor of Cat will be called when the keyword delete is used in the above.

• (The destructor will also be called if the function that creates the object finishes.)

Computer Programming and Basic Software Engineering6. Pointers and Arrays

22

#include <iostream>using namespace std;class SimpleCat{public: SimpleCat(); ~SimpleCat(); int GetAge() const {return itsAge;} void SetAge(int age) {itsAge = age;}private: int itsAge;};SimpleCat::SimpleCat(){ cout << "Constructor called.\n"; itsAge = 1;}SimpleCat::~SimpleCat(){ cout << "Destructor called.\n";}

The class SimpleCat

Constructor

Destructor

Example

Computer Programming and Basic Software Engineering6. Pointers References and Arrays

23

int main(){

cout << "SimpleCat Frisky...\n";SimpleCat Frisky;cout << "SimpleCat *pRags = new SimpleCat...\n";SimpleCat * pRags = new SimpleCat;cout << "delete pRags...\n";delete pRags;cout << "Exiting, watch Frisky go...\n";return 0;

}

Output of the program

Computer Programming and Basic Software Engineering6. Pointers and Arrays

pRags in the stack, *pRags in the heap

24

Accessing Members of Objects• To access members of an object, the symbol (.) is used.

SimpleCat *pCat = new SimpleCat;

(*pCat).SetAge(2);

The object pointed by pCat

The member function of the

object

Input parameter of the member

function

• In C++, a shorthand is provided for such member access

SimpleCat *pCat = new SimpleCat;

pCat->SetAge(2); // The same as before

The Same

The Same

Computer Programming and Basic Software Engineering6. Pointers and Arrays

25

6. Pointers and Arrays#include <iostream>using namespace std;class Object{public: Object(); ~Object(); int GetCnt() const {return *count;}private: int *count;};Object::Object(){ count = new int(1);} // initialize *count to 1Object::~Object(){ delete count;}int main(){ Object Obj; return 0;}

Question

If I declare an object in the stack that has member variables in the heap, what is in the stack and what is in the heap?

Computer Programming and Basic Software Engineering

26

Answer4 bytes on the stack to hold Obj which contains a pointer count.

4 bytes on the heap that is pointed by count of Obj.

Free Storeor

the heap

Global Name SpaceCode SpaceThe Stack4 bytes: count

4 bytes: *count

ObjObj

Computer Programming and Basic Software Engineering6. Pointers and Arrays

27

0000 0001 0002 0003 0004 0005 0006 0007 0008 0009

Pointers Arithmetic• Pointers can be added or subtracted from one another if

they are of the same type.

Address

Memory

Variables short int *a, *b

10 0A 21 3A 51 44 20

cout << "a = " << a << endl; // Assume a = 0000

b = a + 1;

cout << "b = " << b << endl; // b = 0002

cout << "b - a = " << b-a << endl; // b - a = 1

Computer Programming and Basic Software Engineering6. Pointers and Arrays

28

Pointers Arithmetic• The same applies to objects.

0000 0001 0002 0003 0004 0005 0006 0007 0008 0009Address

Memory

Variables Cat *a = new Cat; //Assume Cat takes 6 bytes

Cat *a = new Cat;Cat *b;cout << "a = " << a << endl; // Assume a = 0000b = a + 1;cout << "b = " << b << endl; // b = 0006cout << "b - a = " << b-a << endl; // b - a = 1

Computer Programming and Basic Software Engineering6. Pointers and Arrays

You should not DIRECTLY assign a value to a pointer, e.g.

int *p=0x00110110;

29

Exercise 6.1bFind out the errors in the following programs. Note the error messages when you build these program. Fix the errors and rebuild it to verify your corrections.

#include <iostream>using namespace std;int main(){ int *pInt; *pInt = 9; cout << "The value at pInt: "

<< *pInt << endl; return 0;}

#include <iostream>using namespace std;int main(){ int SomeVariable = 5; cout << "SomeVariable: "

<< SomeVariable << "\n"; int *pVar = & SomeVariable; pVar = 9; cout << "SomeVariable: " << *pVar << "\n"; return 0;}

Computer Programming and Basic Software Engineering6. Pointers and Arrays

30

Exercise 6.1cModify the program you wrote in exercises 5.2 a and b such that

a. The program will ask the user if he wants to create the object Felix. If yes, the object is created in the heap. If no, just quit.

b. As before, initialize the age and weight of Felix to 5 and 10 using the constructor. Display the age and weight of Felix.

c. Ask the user to enter the age and weight of Felix and display them again.

d. After printing the age and weight of Felix, the program will repeatedly ask the user whether he wants to (i) enter the age and weight again; (ii) destroy Felix and create again; or (iii) quit the program. Your program should be able to perform the task the user selected.

e. Whenever Felix is destroyed, print the current age and weight of Felix using the destructor.

f. Comment your program appropriately.

Computer Programming and Basic Software Engineering6. Pointers and Arrays

31

Acknowledgments

The slides are based on the set developed by Dr. Frank Leung (EIE).