Writing a Good Program 6. Pointers and Arrays 1

Download Report

Transcript Writing a Good Program 6. Pointers and Arrays 1

1
Writing a Good Program
6. Pointers and Arrays
2
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
6.1 Pointers
3
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
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
How memory is used in C++?
main()
{ Statements;
funcA();
Statements;
funcB();
Statements;
}
funcA()
{ int a;
return;
}
funcB()
{ Cat Frisky;
return;
}
Free Store
or
the heap
The Stack
Code Space
Global Name Space
5
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. Each byte has an address
• Every variable has a memory address.
Variables char a
Memory
Address
a = 30
int b
30 0A 21 3A
Each variable has the
starting-byte address
short int c
bool d
51
00
44 20
0100 0101 0102 0103 0104 0105 0106 0107 0108 0109
The character '0'
Address of a = 0100
b = 0A 21 3A 51 Address of b = 0101
c = 44 20
Address of c = 0105
All values written in
hexadecimal but
binary in reality
6
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
What is the Address of a Variable?
• In C++, the symbol & is used to indicate the address of a
#include <iostream>
variable.
The addresses of
shortVar,
longVar and
sVar
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;
}
7
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
Memory
Address
int b
10 0A 21 3A
(address of a) pa
51
00
00
01
00
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
6. 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
 How about
(address of a character) pa;
Better, but look too clumsy
10
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
What is a Pointer?
• C++ uses an elegant way to solve the problem (but need some
time to understand!).
pa's content is an address, the memory
content of that address is a character
• It introduces a symbol *.
 means the content of an address.
Variables char a
Memory
Address
int b
10 0A 21 3A
char *pa
51
00
00
01
00
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
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
What is a Pointer?
• We can modify the content of a memory location using pointer.
Variables char a
Memory
Address
int b
30 0A 21 3A
char *pa
51
00
00
01
00
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;
cout << "myAge: " << myAge << "\n";
cout << "*pAge: " << *pAge << "\n";
return 0;
}
13
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
14
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
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.
15
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
new and delete
The keywords new and delete help us claim and release
memory in Free Store.
Claim a piece of memory in
unsigned short int * pPointer;
Free Store with size that is
pPointer = new unsigned short int;
equal to an unsigned short
:
integer.
// 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
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
int * pPointer;
unsigned short int * pPointer2;
pPointer = 8004
pPointer = new int;
:
pPointer2 = new unsigned short int [2]; pPointer2 = 8008
:
delete pPointer; // return it to system
delete [] pPointer2; // return it to system
Free Store
Memory
Address
8003 8004 8005 8006 8007 8008 8009 800A 800B 800C
17
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
Exercise 6.1
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 Runtime Debugger. Answer the following questions:
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
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;
cout << "*pHeap: " << *pHeap << "\n";
delete pHeap;
delete pHeap;
return 0;
}
19
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
Stray (Wild or Dangling) Pointers
• When one deletes a pointer, the associated memory will be
given back to system.
delete a pointer ≠ remove a pointer, it still exists
• If one tries to use that pointer again without reassigning it,
the result is unpredictable.
NULL points to ROM
• 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
20
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
Creating Objects in the Free Store
• Similar to integer, we
can create objects in
the Free Store.
Cat *pCat = new Cat;
• pCat stores the
beginning address of
the memory allocated.
• When the object is
created, its
constructor is called.
Object identified by a pointer.
Size enough for a Cat
pCat
Free Store
or
the heap
The Stack
Code Space
Global Name Space
21
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
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;
pRags in
cout << "delete pRags...\n";
the stack,
delete pRags;
cout << "Exiting, watch Frisky go...\n"; *pRags in
return 0;
the heap
}
Output of the
program
24
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 member
The object
pointed by pCat 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
and Arrays
#include6. Pointers
<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
4 bytes: *count
Free Store
or
the heap
Obj
4 bytes: count The Stack
Code Space
Global Name Space
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.
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
Address
10 0A 21 3A 51 44 20
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
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
Pointers Arithmetic
• The same applies to objects.
You should not DIRECTLY assign a
value to a pointer, e.g.
int *p=0x00110110;
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 *b;
cout << "a =
b = a + 1;
cout << "b =
cout << "b -
Cat;
" << a << endl;
// Assume a = 0000
" << b << endl;
a = " << b-a << endl;
// b = 0006
// b - a = 1
29
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
Exercise 6.1b
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
Computer Programming and Basic Software Engineering
6. Pointers and Arrays
Exercise 6.1c
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).