Nothing Special   »   [go: up one dir, main page]

Lec03-04 (Topic 2 Arrays and Pointers) - v2

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 94

Lecture 3

Arrays and Pointers


3.1 Introduction to one-dimensional arrays

3.2 Two-dimensional arrays

1
Introduction to one-dimensional arrays
3.1

2
Introduction to Arrays
• An array is used to process a collection of data
of the same type
– Examples:
A list of names
A list of temperatures

• Why do we need arrays?


– Imagine keeping track of 5 test scores, or 100, or 1000 in
memory
• How would you name all the variables?
• How would you process each of the variables?
3
Declaring an Array
• An array, named score, containing five variables of type int can be declared as:
int score[5];

Syntax: Type_Name Array_Name[Declared_Size];

Type_Name - can be any type


Declared_Size – the size of the array

• The example above is like declaring 5 variables of type int:


score[0], score[1], … , score[4]

• The value in brackets is called:


– A subscript
– An index

4
The Array Variables
• The variables making up the array are referred to as
– Indexed variables
– Subscripted variables
– Elements of the array int score[5];

• The number of indexed variables in an array is the


declared size or size of the array
– The largest index is one less than the size
– The first index value is zero

Score[5]
[0] [1] [2] [3] [4] 5
Array Variable Types
• An array can have indexed variables of any
type

• All indexed variables in an array are of the


same type
– This is the base type of the array

• An indexed variable can be used anywhere


an ordinary variable of the base type is used
6
Using [ ] With Arrays
• In an array declaration, [ ]'s enclose the size of the
array such as this array of 5 integers:
int score [5];

• When referring to one of the indexed variables, the []'s


enclose a number identifying one of the indexed variables
– score[3] is one of the indexed variables

Score[5]
[0] [1] [2] [3] [4]
– The value in the []'s can be any expression that evaluates to
one of the integers 0 to (size -1)

7
Indexed Variable Assignment
• To assign a value to an indexed variable, use
the assignment operator:
int n = 2;
score[n + 1] = 99;
– In this example, variable score[3] is assigned 99

Score[5] 99
[0] [1] [2] [3] [4]

8
Initializing Arrays
• To initialize an array when it is declared
– The values for the indexed variables are enclosed in braces and
separated by commas
– Example:
int children[3] = {2, 12, 1};

Is equivalent to:
int children[3];
children[0] = 2;
children[1] = 12;
children[2] = 1;

children[3] 2 12 1
[0] [1] [2] 9
Default Values
• If too few values are listed in an initialization statement
– The listed values are used to initialize the first of the indexed
variables
– The remaining indexed variables are initialized to a zero of
the base type
– Example:
int a[10] = {5, 5};
initializes a[0]and a[1] to 5 and a[2] through a[9] to 0

a[10] 5 5 0 0 0 0 0 0 0 0
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

10
Un-initialized Arrays
• If no values are listed in the array declaration,
some compilers will initialize each variable to a zero
of the base type.
– Example:
int a[10];
a[10] 0 0 0 0 0 0 0 0 0 0
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

DO NOT DEPEND ON THIS!


Different compilers have different default settings.
11
Un-initialized Arrays
• Alternatively, a default value can be explicitly
assigned in the statement
– Example:
int a[10] = {0};

a[10] 0 0 0 0 0 0 0 0 0 0
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

12
Loops And Arrays
• For loops are commonly used to step through arrays
Array declaration First index is 0 Last index is (size – 1)

int score[5], max = 0;


for (int i = 0; i < 5; i++)
{
cout << “Enter score of number i+1:”;
cin >> score[i];
if (score[i] > max){
max = score[i]; // fine the max
value
}
}
Score[5] 5 9 2 10 6 10
[0] [1] [2] [3] [4] max
13
Loops And Arrays
• To display the difference between each score and the
maximum score stored in an array
Display each score
for (int i = 0; i < 5; i++)
{
cout << score[i] << “ off by ”;
cout << (max – score[i]) << endl;
}
Display the difference between
the score and max value

14
Loops And Arrays
SAMPLE OUTPUT:
Enter score of number 1: 5
Enter score of number 2: 9
Enter score of number 3: 2
Enter score of number 4: 10
Enter score of number 5: 6
5 off by 5
9 off by 1
2 off by 8
10 off by 0
6 off by 4

15
How Computer Memory manages Array?

• Computer memory consists of numbered locations


called bytes
– A byte's number is its address

• A simple variable is stored in consecutive bytes


– The number of bytes depends on the variable's type

• A variable's address is the address of its first byte

16
Arrays and Memory
• Declaring the array int a[6]
– Reserves memory for six variables of type int
– The variables are stored one after another
– The address of a[0] is remembered
• The addresses of the other indexed variables are not remembered
– Example: To determine the address of a[3]
• Start at the memory address of a[0]
• Count past enough memory for three integers to find a[3]

Starts here

int
a[6]
[0] [1] [2] [3] [4] [5]
Memory 1023 1025 1027 1029 1031 1033 17
address
Slide 7- 18
Programming With Arrays
• The size needed for an array is changeable
– Often varies from one run of a program to another
– Is often not known when the program is written

• A common solution to the size problem


– Declare the array size to be the largest that could
be needed
– Decide how to deal with partially filled arrays

19
Partially Filled Arrays
• When using arrays that are partially filled
– The manipulator of the array may not need to know
the declared size of the array, only how many
elements are going to be stored in the array

– A parameter, number_used, may be sufficient to


ensure that referenced index values are legal

– Then the manipulator of the array only needs to


know the number_used variable
20
Partially Filled Arrays (Example)
#include <iostream>
using namespace std;
int main() { Output 1:
int number_used;
Enter number of elements to use: 21
char array[20];
ERROR!
cout << "Enter number of elements to use: ";
Error: Number of elements cannot greater
cin >> number_used; than size of array!

if(number_used > 20){


cout << "Error: Number of elements cannot greater than size of array!" <<
endl;
exit(1);
}
cout << "\nStart filling array with * symbol..." << endl;
for (int i = 0; i < number_used; i++){
array[i] = '*';
}

cout << "\nDisplay all elements of the array..." << endl;


int i = 0; Output 2:
while(i < number_used){ Enter number of elements to use: 5
cout << array[i] << "";
Start filling array with * symbol...
i++;
}
return 0;
Display all elements of the array...
} ***** 21
Array Index Out of Range
• A common error is using a nonexistent index

• Take the previous example, index values for int a[6] are
the values 0 through 5

• An index value not allowed by the array declaration is out of


range!

• Problem in most compilers: Using an out-of-range index value


does not produce an error message!

22
Out of Range Problems
• If an array is declared as: int a[6];
and an integer is declared as: int i = 7;

• Executing the statement a[i]=238; causes…


– The computer to calculate the address of the illegal a[7]
(This address could be where some other variable is stored)
– The value 238 is stored at the address calculated for a[7]
– No warning is given!

23
Variables and Declarations
• Most compilers do not allow the use of a variable
to declare the size of an array

Example:
cout << "Enter number of students: ";
cin >> number;
int score[number];

This code is illegal on many compilers

• To do this, one must use DYNAMIC ARRAYS!


24
Constants and Arrays
• Use constants to declare the size of an array
• Using a constant allows your code to be easily altered for use
on a smaller or larger set of data
– Example:
const int NUMBER_OF_STUDENTS = 50;
int score[NUMBER_OF_STUDENTS];

for ( i = 0; i < NUMBER_OF_STUDENTS; i++)
cout << score[i] << " off by "<< (max -
score[i]) << endl;
• Only the value of the constant must be changed to make this
code work for any number of students

25
Constants as Arguments
• During the declaration of the array, a constant
maximum size (e.g. MAX_SIZE) is used to determine
the array size

• Using MAX_SIZE as an argument makes it clear


that is the maximum size of the array

• This makes the code easier to read and edit in the


future

26
Constants Variable Size in array (Example)
Just change this value
#include <iostream> when the size of the array
using namespace std; is changed
int main() {
int number_used; int number_used;
char array[20]; const int MAX_SIZE = 20;

char array[MAX_SIZE];
cout << "Enter number of elements to use: ";
cin >> number_used;

if(number_used > 20){ if(number_used > MAX_SIZE){


cout << "Error: Number of elements cannot greater than size of array!" <<
endl;
exit(1);
}
cout << "\nStart filling array with * symbol..." << endl;
for (int i = 0; i < number_used; i++){
array[i] = '*';
}

cout << "\nDisplay all elements of the array..." << endl;


int i = 0;
while(i < number_used){
cout << array[i] << "";
i++;
}
return 0;
} 27
Knowledge Check
• Can you

– Describe the difference between a[4] and a[5]?

– Show the output of

char symbol[3] = {'a', 'b', 'c’};


for (int index = 0; index < 3; index++)
cout << symbol[index];

– Write a program that will read up to 10 letters into an array and write the
letters back to the screen in the reverse order.

E.g. abcd should be output as dcba

Use a period as a sentinel value to mark the end of input.


28
Sample code

29
Two-dimensional arrays
3.2

30
Multi-Dimensional Arrays
• C++ allows arrays with multiple index values
– char page[30][100];
declares an array of characters named page
• page has two index values:
The first ranges from 0 to 29
The second ranges from 0 to 99
– Each index is enclosed in its brackets
– Page can be visualized as an array of 30 rows and
100 columns

31
Index Values of array page
• The indexed variables for the array page are
page[0][0], page[0][1], …, page[0][99]
page[1][0], page[1][1], …, page[1][99]
… … …
page[29][0], page[29][1], … , page[29][99]

• page is an array of size 30


– page's base type is an array of 100 characters

32
Visualization of array page[30][100]
Column
[0] [1] [2] [3] …… [99]

[0] [0][0] [0][1] [0][2] [0][3] …… …… …… [0][99]

[1] [1][0] [1][1] [1][2] [1][3] …… …… …… [1][99]

[2] [2][0] [2][1] [2][2] [2][3] …… …… …… [2][99]

Row
……

[29] [29][0] [29][1] [29][2] [29][3] …… …… …… [29][99]

33
Program Example: Grading Program
• Grade records for a class can be stored in a two-
dimensional (2D) array
– For a class with 4 students and 3 quizzes the array could be
declared as

int grade[4][3];

• The first array index refers to the number of students


• The second array index refers to the number of quizzes

• Since student and quiz numbers start with one,


we subtract one to obtain the correct index
34
Visualization of 2D Array grade
Condition: 4 students and 3 quizzes

Column - Quizzes
[0] [1] [2]

[0] [0][0] [0][1] [0][2]


Row – Students

[1] [1][0] [1][1] [1][2]

[2] [2][0] [2][1] [2][2]

[3] [3][0] [3][1] [3][2]

35
Grading Program: Average scores
• The grading program uses one-dimensional
arrays to store…
– Each student's average score
– Each quiz's average score

• The loops that calculate these averages use


global constants for the size of the arrays
– This was done to improve clarity and increase the
ease of edit
36
37
Visualization of 2D Array grade – After
the grades are inserted
Condition: 4 students and 3 quizzes

Column - Quizzes
[0] [1] [2]

[0] 2 4 6
Row – Students

[1] 3 7 10

[2] 5 4 1

[3] 2 0 8

38
39
Visualization of 2D Array grade – Count
student’s average
Condition: 4 students and 3 quizzes

Column - Quizzes int sum;

[0] [1] [2] 12

[0] 2 4 6 /3
Row – Students

float StudentAvg[MAX_STUDENT];
[1] 3 7 10
4
[2] 5 4 1 [0] [1] [2] [3]

[3] 2 0 8

40
Visualization of 2D Array grade – Count
student’s average
Condition: 4 students and 3 quizzes

Column - Quizzes int sum;

[0] [1] [2] 20

[0] 2 4 6 /3
Row – Students

float StudentAvg[MAX_STUDENT];
[1] 3 7 10
4 6.67
[2] 5 4 1 [0] [1] [2] [3]

[3] 2 0 8

41
Visualization of 2D Array grade – Count
quiz’s average
Condition: 4 students and 3 quizzes

Column - Quizzes int sum;

[0] [1] [2] 12

[0] 2 4 6 /4
Row – Students

float QuizAvg[MAX_QUIZ];
[1] 3 7 10
3
[2] 5 4 1 [0] [1] [2]

[3] 2 0 8

42
Visualization of 2D Array grade – Count
quiz’s average
Condition: 4 students and 3 quizzes

Column - Quizzes int sum;

[0] [1] [2] 15

[0] 2 4 6 /4
Row – Students

float QuizAvg[MAX_QUIZ];
[1] 3 7 10
3 3.75
[2] 5 4 1 [0] [1] [2]

[3] 2 0 8

43
44
45
Lecture 4

Arrays and Pointers


4.1 Sorting & Searching

4.2 Pointers

46
Sorting & Searching
4.1

47
Searching Arrays
• A sequential search is one way to search an
array for a given value
– Look at each element from first to last to see if the
target value is equal to any of the array elements
– The index of the target value can be returned to
indicate where the value was found in the array
– A value of -1 can be returned if the value was not
found

48
The search Function
• The search
– Uses a while loop to compare array elements to
the target value
– Uses the found variable as a condition for loop
termination as well
– At the end of the loop, processes output based on
the found variable again

49
50
51
Program Example:
Sorting an Array
• Sorting a list of values is a very common task
– Create an alphabetical listing
– Create a list of values in ascending order
– Create a list of values in descending order

• Many sorting algorithms exist


– Some are very efficient
– Some are easier to understand

• Example
– Bubble sort, selection sort, insertion sort, merge sort, quick sort,
heap sort, etc
52
Program Example:
The Selection Sort Algorithm
• When the sort is complete, the elements of the array are ordered
such that

a[0] < a[1] < … < a [ number_used -1]

– …ascending order

– This leads to an outline of an algorithm:


for (int index = 0; index < number_used; index++)
place the indexth smallest element in a[index]

– Essentially is sorting the smallest elements to the front

53
Program Example:
Sort Algorithm Development
• One array is sufficient to do our sorting
1. Search for the smallest value in the array

2. Place this value in a[0], and place the value that was in
a[0] in the location where the smallest was found

3. Starting at a[1], find the smallest remaining value and


swap it with the value currently in a[1]

4. Starting at a[2], continue the process until the array is


sorted
54
Slide 7- 55
56
57
Pointers
4.2

58
Pointers
• A pointer is the memory address of a variable
• Memory addresses can be used as names for
variables
– If a variable is stored in three memory locations,
the address of the first can be used as a name for
the variable.
– When a variable is used as a call-by-reference
argument, its address is passed

59
Pointers Tell
Where To Find A Variable

• An address used to tell where a variable is


stored in memory is a pointer

– Pointers "point" to a variable by telling where the


variable is located

60
Declaring Pointers
• Pointer variables must be declared to have a
pointer type
– Example: To declare a pointer variable p that can
"point" to a variable of type double:

double *p;
– The asterisk identifies p as a pointer variable

61
Let's assign a value of 3 to variable a. Since p is meant for storing
address, we store the address of variable a into variable p.
1432

Basics of int a;
we get... 3 a [ int ]

Pointers int* p; 4324


a = 3; 1432 p [ int* ]
p = &a;

the address of variable a is


Here, the ampersand is called address operator
now stored here.
which returns the address of variable a

We now say that the value of variable p is the address of variable a.


DO NOT BE CONFUSED, since p is itself a variable, it has its own address too.
In our example above :
p has a value of 1432, which is to say, p has the value of &a (address of a)
BUT &p has a value of 4324

62
Multiple Pointer Declarations
• To declare multiple pointers in a statement,
use the asterisk before each pointer variable
– Example:

int *p1, *p2, v1, v2;

p1 and p2 point to variables of type int


v1 and v2 are variables of type int

63
The address of Operator
• The & operator can be used to determine the
address of a variable which can be assigned to a
pointer variable
– Example: V1
[int]
int *p1, v1; 1220
Pointed to
p1 = &v1;
*p1
v1 address is assigned [int]
1220
into pointer p1 4300

p1 is now a pointer to v1
v1 can be called v1 or "the variable pointed to by p1"
64
The Dereferencing Operator
• C++ uses the * operator in yet another way
with pointers
– The phrase "The variable pointed to by p" is
translated into C++ as *p
– Here the * is the dereferencing operator
• p is said to be de-referenced

65
A Pointer Example
int v1, *p1;
v1 and *p1 now refer to
v1 = 0; the same variable
p1 = &v1;
*p1 = 42;
cout << v1 << endl;
cout << *p1 << endl;
1011 2122
Pointing
42
0 1011
output: to
*p1
42 v1

42
66
Pointer Assignment
• The assignment operator = is used to assign the value of one
pointer to another 1207
– Example: 1011
If p1 still points to v1 (previous slide) then *p2
Pointing
to
int *p2; 1011 2122
Pointing
p2 = p1; 42 1011
to
v1 *p1

causes *p2, *p1, and v1 all to name the same variable

– What is the value of pointers?


67
Caution! Pointer Assignments
• Some care is required in making assignments to pointer
variables

– p1= p3;  changes the location (memory address)


that p1 "points" to

– *p1 = *p3; changes the value at the location that


p1 "points" to

68
69
1011 2122
More example: Pointing to
10 1011
#include <iostream>
using namespace std; x *p1
int main() {
Must have int x=10, y=20;
5100 1333
bracket, int* p1; Pointing to
without them it int* p2; 20 5100
p1 = &x;
means *(p1+ y *p2
p2 = &y;
+)
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
(*p1)++; /* equals to x++; */
*p2 += 4; /* equals to y+=4; */
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
p1 = p2;
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
p2 = &x;
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
}

output: 10 20 10 20
p1 now also points to y. 11 24 11 24
11 24 24 24
11 24 24 11 70
1011 2122
More example: Pointing to
11 1011
#include <iostream>
using namespace std; x *p1
int main() {
Must have int x=10, y=20;
5100 1333
bracket, int* p1; Pointing to
without them it int* p2; 24 5100
p1 = &x;
means *(p1+ y *p2
p2 = &y;
+)
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
(*p1)++; /* equals to x++; */
*p2 += 4; /* equals to y+=4; */
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
p1 = p2;
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
p2 = &x;
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
}

output: 10 20 10 20
p1 now also points to y. 11 24 11 24
11 24 24 24
11 24 24 11 71
1011 2122
More example: 11 5100
#include <iostream>
using namespace std; x Pointing to *p1
int main() {
Must have int x=10, y=20;
5100 1333
bracket, int* p1; Pointing to
without them it int* p2; 24 5100
p1 = &x;
means *(p1+ y *p2
p2 = &y;
+)
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
(*p1)++; /* equals to x++; */
*p2 += 4; /* equals to y+=4; */
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
p1 = p2;
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
p2 = &x;
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
}

output: 10 20 10 20
p1 now also points to y. 11 24 11 24
11 24 24 24
11 24 24 11 72
1011 2122
More example: 11 5100
#include <iostream>
using namespace std; x Pointing to *p1
int main() {
Must have int x=10, y=20;
5100 1333
bracket, int* p1;
Pointing to
without them it int* p2; 24 1011
p1 = &x;
means *(p1+ y *p2
p2 = &y;
+)
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
(*p1)++; /* equals to x++; */
*p2 += 4; /* equals to y+=4; */
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
p1 = p2;
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
p2 = &x;
cout << x << " " << y << " " << *p1 << " " << *p2 << endl;
}

output: 10 20 10 20
p1 now also points to y. 11 24 11 24
11 24 24 24
11 24 24 11 73
Pointers and Constants
Pointer to Constant

const int n = 3; n is constant


int* p;
p = &n;

A pointer of type [int *] CANNOT point to a value


of type [const int].
INVALID

74
Pointer p has the type
int z = 1; [const int *]
const int n = 3;
const int* p;
p = &n;

*p = 5;
z = *p + 3;
INVALID. A pointer of type
p = &z;
[const int *] CANNOT be
*p = 10; used to MODIFY the value it is
z = 10; pointing to.

CONCLUSION: A pointer of type [const int *] is a Read-Only Pointer.

75
Constant Pointer
p has a type [int * const]
meaning that it is a constant
pointer, the value it is pointing to
int m,n; is not constant, but p itself is a
int * const p = &n; constant and can not be
changed
*p = 10;
p must be initialized (just as any
n = 5;
p = &m;
constant variable must be
initialized)

INVALID. A pointer of type [int * const] is a


constant pointer and CANNOT be modified (can
not be reassigned to point to another variable).

76
Pointers and Arrays
assign the value of n (address of
The name of the array is actually a constant the first element of the array) to p.
pointer pointing to the address of the first
element in the array !! output:

1 4 3
int n[5] = {1,4,3,8,7}; 1 4 3
int *p; 43 82 58
p = n; 2650
43 82 58

cout <<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; 1100 n[0]


cout <<p[0]<<" "<<p[1]<<" "<<p[2]<<endl; 1100 1 [int]
n
[ int[5] ] n[1]
p[0]=43; p[1]=82; p[2]=58; 1104 4 [int]

3664 n[2]
cout <<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; 1108 3 [int]
cout <<p[0]<<" "<<p[1]<<" "<<p[2]<<endl; 1100 n[3]
1112 8 [int]
p
[] is called Subscript operator [ int* ] n[4]
1116 7 [int]
Pointer p behaves and can be used just like an array.
77
Now p is pointing at the address of the
output:
element 2 of the array n.
1 4 3
int n[5] = {1,4,3,8,7}; 3 8 7
int *p; 1 4 43
p = &n[2]; 43 82 58
2650

cout <<n[0]<<" "<<n[1]<<" "<<n[2]<<endl;


1100 n[0]
cout <<p[0]<<" "<<p[1]<<" "<<p[2]<<endl; 1100 1 [int]
p[0]=43; p[1]=82; p[2]=58; n
[ int[5] ] n[1]
cout <<n[0]<<" "<<n[1]<<" "<<n[2]<<endl; 1104 4 [int]
cout <<p[0]<<" "<<p[1]<<" "<<p[2]<<endl;
3664 n[2]
1108 3 [int]
Pointer p still behaves like an array, but this time it 1108 n[3]
starts only at element n[2]. 1112 8 [int]
p
[ int* ] n[4]
p[0] is equivalent to n[2], 1116 7 [int]
p[1] is equivalent to n[3],
p[2] is equivalent to n[4],
p[i] is equivalent to n[i + 2]
78
Pointer Addition and Subtraction

Consider :

int n[] = {1,4,3,8,7,2,5,9};


int *p; output:
p = &n[1]; 4 3 8
cout <<p[0]<<" "<<p[1]<<" "<<p[2]<<endl; 3 8 7
p++; cout <<p[0]<<" "<<p[1]<<" "<<p[2]<<endl; 7 2 5
p+=2; cout <<p[0]<<" "<<p[1]<<" "<<p[2]<<endl; 8 7 2
p--; cout <<p[0]<<" "<<p[1]<<" "<<p[2]<<endl; 1 4 3
p-=3; cout <<p[0]<<" "<<p[1]<<" "<<p[2]<<endl;

Whenever we add a number to the pointer, we are actually making the


pointer to move a certain number of position in the simulated "array".

79
Consider : output 2650
4 3 8
4 1100
int n[] = {1,4,3,8,7,2 }; 3
int *p; 8 n
[ int[6] ]
p = &n[1]; 7 2 n[0]
23 76 1100 1 [int]
cout <<p[0]<<" "<<p[1]<<" "<<p[2]<<endl;
3862
cout << *p << endl; n[1]
cout << *(p+1) << endl; 1104 4 [int]
1104
cout << *(p+2) << endl; n[2]
p 1108 3 [int]
[ int* ]
cout <<p[3]<<" "<<p[4]<<endl; n[3]
*(p+3) = 23; 1112 8 [int]
p+1
*(p+4) = 76; n[4]
cout <<p[3]<<" "<<p[4]<<endl; 1116 7 [int]
p+2
n[5]
1120 2 [int]

If you add 1 to a pointer, it only means moving 1 position (that is 1 element


of the array) in the "simulated" array.

80
The new Operator
• Using pointers, variables can be manipulated
even if there is no identifier for them
– To create a pointer to a new "nameless" variable of
type int:
p1 = new int;
– The new variable is referred to as *p1
– *p1 can be used any place an integer variable can
cin >> *p1;
*p1 = *p1 + 7;

81
Dynamic Variables
• Variables created using the new operator are
called dynamic variables
– Dynamic variables are created and destroyed
while the program is running
– Also called dynamic memory allocation (DMA)

82
Slide 9- 83
84
Basic Memory Management
• An area of memory called the freestore is
reserved for dynamic variables
– New dynamic variables use memory in the freestore
– If all of the freestore is used, calls to new will fail

• Unneeded memory can be recycled


– When variables are no longer needed, they can be
deleted and the memory they used is returned to
the freestore

85
The delete Operator
• When dynamic variables are no longer
needed, delete them to return memory to the
freestore
– Example:
delete p;

The value of p is now undefined and the memory


used by the variable that p pointed to is back in
the freestore

86
Dangling Pointers
• Using delete on a pointer variable destroys the
dynamic variable pointed to.

• If another pointer variable was pointing to the


dynamic variable, that variable is also undefined.

• Undefined pointer variables are called dangling


pointers
– Dereferencing a dangling pointer (*p) is usually
disastrous
87
Dangling Pointers (Example)
int main() {
int *ptr = new int;
*ptr = 5;
cout << "At first *ptr is " << *ptr << endl;
delete ptr;
cout << "After delete *ptr is " << *ptr << endl;
ptr = new int;
*ptr = 99;
cout << "Lastly, *ptr is " << *ptr << endl;
return 0;
}
Sample output 1: Sample output 2:
At first *ptr is 5 At first *ptr is 5
After delete *ptr is 0 After delete *ptr is 10030968
Lastly, *ptr is 99 Lastly, *ptr is 99

Depending on compilers!! 88
Type Definitions
• A name can be assigned to a type definition, then used
to declare variables

• The keyword typedef is used to define new type


names
– Syntax:

typedef Known_Type_Definition New_Type_Name;

• Known_Type_Definition can be any type

89
Defining Pointer Types
• To avoid mistakes using pointers, define a pointer type name
– Example:
typedef int* IntPtr;

Defines a new type, IntPtr, for pointer variables


containing pointers to int variables

IntPtr p;
is equivalent to
int *p;

90
Multiple Declarations Again
• Using our new pointer type defined as

typedef int* IntPtr;

Prevent this error in pointer declaration:


int *P1, P2; // Only P1 is a pointer variable
with
IntPtr P1, P2; // P1 and P2 are pointer variables

91
Pointer Reference Parameters
• A second advantage in using typedef to define a pointer
type is seen in parameter lists
– Example:

void sample_function(IntPtr& pointer_var);

is less confusing than

void sample_function(int*& pointer_var);

92
Knowledge Check
• Can you
– Declare a pointer variable?
– Assign a value to a pointer variable?
– Use the new operator to create a new variable in the
freestore?
– Write a definition for a type called NumberPtr to be a
type for pointers to dynamic variables of type int?
– Use the NumberPtr type to declare a pointer variable
called my_point?

93
C++ Fundamentals -- End

Slides adapted from


Walter Savitch, “Problem
solving with C++”

94

You might also like