Lec03-04 (Topic 2 Arrays and Pointers) - v2
Lec03-04 (Topic 2 Arrays and Pointers) - v2
Lec03-04 (Topic 2 Arrays and Pointers) - v2
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
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];
Score[5]
[0] [1] [2] [3] [4] 5
Array Variable Types
• An array can have indexed variables of any
type
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]
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)
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?
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
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
• Take the previous example, index values for int a[6] are
the values 0 through 5
22
Out of Range Problems
• If an array is declared as: int a[6];
and an integer is declared as: int i = 7;
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];
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
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;
– 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.
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]
32
Visualization of array page[30][100]
Column
[0] [1] [2] [3] …… [99]
Row
……
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];
Column - Quizzes
[0] [1] [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
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
[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
[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
[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
[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
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
• 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
– …ascending order
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
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
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 ]
62
Multiple Pointer Declarations
• To declare multiple pointers in a statement,
use the asterisk before each pointer variable
– Example:
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
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
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.
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)
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
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
Consider :
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]
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
85
The delete Operator
• When dynamic variables are no longer
needed, delete them to return memory to the
freestore
– Example:
delete p;
86
Dangling Pointers
• Using delete on a pointer variable destroys the
dynamic variable pointed to.
Depending on compilers!! 88
Type Definitions
• A name can be assigned to a type definition, then used
to declare variables
89
Defining Pointer Types
• To avoid mistakes using pointers, define a pointer type name
– Example:
typedef int* IntPtr;
IntPtr p;
is equivalent to
int *p;
90
Multiple Declarations Again
• Using our new pointer type defined as
91
Pointer Reference Parameters
• A second advantage in using typedef to define a pointer
type is seen in parameter lists
– Example:
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
94