Presentation is loading. Please wait.

Presentation is loading. Please wait.

Writing a Good Program 6. Pointers and Arrays

Similar presentations


Presentation on theme: "Writing a Good Program 6. Pointers and Arrays"— Presentation transcript:

1 Writing a Good Program 6. Pointers and Arrays

2 6.1 Pointers Computer Programming and Basic Software Engineering
6. Pointers and Arrays 6.1 Pointers

3 How memory is used in C++?
Computer Programming and Basic Software Engineering 6. Pointers and Arrays 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 store - for the storage of dynamically created data

4 How memory is used in C++?
Computer Programming and Basic Software Engineering How memory is used in C++? 6. Pointers and Arrays funcB() { Cat Frisky; return; } funcA() { int a; main() { Statements; funcA(); Statements; funcB(); Free Store or the heap Global Name Space Code Space The Stack

5 What is the Address of a Variable?
Computer Programming and Basic Software Engineering 6. Pointers and Arrays What is the Address of a Variable? A variable is a storage space in memory. Every variable has a memory address. Each byte has an address Each variable has the starting-byte address Variables char a int b short int c bool d Memory 30 0A 21 3A 51 44 20 00 Address 0100 0101 0102 0103 0104 0105 0106 0107 0108 0109 The character '0' a = Address of a = 0100 b = 0A 21 3A 51 Address of b = 0101 c = Address of c = 0105 All values written in hexadecimal but binary in reality

6 The addresses of shortVar, longVar and sVar
Computer Programming and Basic Software Engineering What is the Address of a Variable? 6. Pointers and Arrays 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 = ; 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

7 What is the Address of a Variable?
Computer Programming and Basic Software Engineering 6. Pointers and Arrays What is the Address of a Variable? Variable and address of a variable are different.

8 Computer Programming and Basic Software Engineering
6. Pointers and Arrays What is a Pointer? In many situations, we want to store the address of a variable into a particular memory location. Variables char a int b (address of a) pa Memory 10 0A 21 3A 51 00 00 01 00 Address 0100 0101 0102 0103 0104 0105 0106 0107 0108 0109 pa is the pointer of a 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 .

9 Computer Programming and Basic Software Engineering
What is a Pointer? 6. Pointers and Arrays 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  How about (address of a character) pa; Better, but look too clumsy

10 Computer Programming and Basic Software Engineering
What is a Pointer? 6. Pointers and Arrays 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. pa's content is an address, the memory content of that address is a character Variables char a int b char *pa Memory 10 0A 21 3A 51 00 00 01 00 Address 0100 0101 0102 0103 0104 0105 0106 0107 0108 0109 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.

11 We modify a indirectly by using its address
Computer Programming and Basic Software Engineering What is a Pointer? 6. Pointers and Arrays We can modify the content of a memory location using pointer. Variables char a int b char *pa Memory 30 0A 21 3A 51 00 00 01 00 Address 0100 0101 0102 0103 0104 0105 0106 0107 0108 0109 char *pa, a=0x30; // 48 cout << a; // a = '0' pa = &a; // pa = 0100 cout << *pa; // *pa = 30 *pa = 49; // a = '1' cout << a; We modify a indirectly by using its address

12 Computer Programming and Basic Software Engineering
6. 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 pAge cout << "*pAge: " << *pAge << "\n\n"; cout << "*pAge = 7\n"; *pAge = 7; // *pAge=7, not pAge=7, sets myAge to 7 cout << "*pAge: " << *pAge << "\n"; cout << "myAge: " << myAge << "\n\n"; cout << "myAge = 9\n"; myAge = 9; return 0; }

13 Computer Programming and Basic Software Engineering
6. Pointers and Arrays

14 Why Pointer? - Using Free Store
Computer Programming and Basic Software Engineering Why Pointer? - Using Free Store 6. Pointers and Arrays 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.

15 Computer Programming and Basic Software Engineering
new and delete 6. Pointers and Arrays The keywords new and delete help us claim and release memory in Free Store. Claim a piece of memory in Free Store with size that is equal to an unsigned short integer. unsigned short int * pPointer; pPointer = new unsigned short int; : // after using the memory space delete pPointer; // return it to system We claim memory with size equals to 2 integers. pPointer2 now points to the starting address of this memory space. int * pPointer2; pPointer2 = new int[2]; : // after using the memory space delete [] pPointer2; // return it to system Results unpredictable is no []

16 pPointer = 8004 Free Store Memory Address
Computer Programming and Basic Software Engineering 6. Pointers and Arrays 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 = 8004 pPointer2 = 8008 Free Store Memory Address 8003 8004 8005 8006 8007 8008 8009 800A 800B 800C

17 Computer Programming and Basic Software Engineering
Exercise 6.1 6. Pointers and Arrays The 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: What is the address of localVariable? What is the value of pHeap after executing line 6? What is the value of pHeap after executing line 11? 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 Computer Programming and Basic Software Engineering
6. Pointers and Arrays #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; delete pHeap; return 0; }

19 delete a pointer ≠ remove a pointer, it still exists
Computer Programming and Basic Software Engineering Stray (Wild or Dangling) Pointers 6. Pointers and Arrays 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. delete a pointer ≠ remove a pointer, it still exists NULL points to ROM 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

20 Creating Objects in the Free Store
Computer Programming and Basic Software Engineering Creating Objects in the Free Store 6. Pointers and Arrays Similar to integer, we can create objects in the Free Store. Free Store or the heap Size enough for a Cat Cat *pCat = new Cat; pCat pCat stores the beginning address of the memory allocated. When the object is created, its constructor is called. The Stack Object identified by a pointer. Code Space Global Name Space

21 Deleting Objects Objects in the Free Store can also be deleted.
Computer Programming and Basic Software Engineering 6. Pointers and Arrays 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.)

22 Example The class SimpleCat Constructor Destructor
Computer Programming and Basic Software Engineering 6. Pointers References and Arrays #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"; Example The class SimpleCat Constructor Destructor

23 Computer Programming and Basic Software Engineering
6. Pointers and Arrays 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; } pRags in the stack, *pRags in the heap Output of the program

24 Accessing Members of Objects
Computer Programming and Basic Software Engineering 6. Pointers and Arrays Accessing Members of Objects To access members of an object, the symbol (.) is used. The Same 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

25 Computer Programming and Basic Software Engineering
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 1 Object::~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?

26 Computer Programming and Basic Software Engineering
6. Pointers and Arrays Answer Free Store or the heap 4 bytes on the stack to hold Obj which contains a pointer count. 4 bytes on the heap that is pointed by count of Obj. 4 bytes: *count Obj The Stack 4 bytes: count Code Space Global Name Space

27 Computer Programming and Basic Software Engineering
6. Pointers and Arrays Pointers Arithmetic Pointers can be added or subtracted from one another if they are of the same type. Variables short int *a, *b Memory 10 0A 21 3A 51 44 20 Address 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 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

28 Pointers Arithmetic The same applies to objects. Memory Address
Computer Programming and Basic Software Engineering Pointers Arithmetic 6. Pointers and Arrays You should not DIRECTLY assign a value to a pointer, e.g. int *p=0x ; The same applies to objects. Variables Cat *a = new Cat; //Assume Cat takes 6 bytes Memory Address 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 Cat *a = new Cat; Cat *b; cout << "a = " << a << endl; // Assume a = 0000 b = a + 1; cout << "b = " << b << endl; // b = 0006 cout << "b - a = " << b-a << endl; // b - a = 1

29 Computer Programming and Basic Software Engineering
Exercise 6.1b 6. Pointers and Arrays Find 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; }

30 Exercise 6.1c Computer Programming and Basic Software Engineering
6. Pointers and Arrays Modify 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.

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


Download ppt "Writing a Good Program 6. Pointers and Arrays"

Similar presentations


Ads by Google