Lec03-04 (Topic 2 Arrays and Pointers)
Lec03-04 (Topic 2 Arrays and Pointers)
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
Declaring an Array
• An array, named score, containing five variables
of type int can be declared as
int score[ 5 ];
int n = 2;
score[n + 1] = 99;
9
Loops And Arrays
• for-loops are commonly used to step through
arrays First index is 0 Last index is (size – 1)
12
Variables and Declarations
• Most compilers do not allow the use of a variable
to declare the size of an array
– Type_Name Array_Name[Declared_Size];
15
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 is not
remembered
– To determine the address of a[3]
• Start at a[0]
• Count past enough memory for three integers to find
a[3]
16
Slide 7- 17
Array Index Out of Range
• A common error is using a nonexistent index
– 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
– Using an out of range index value doe not produce
an error message!
18
Out of Range Problems
• If an array is declared as: int a[6];
and an integer is declared as: int i = 7;
21
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
– DO NOT DEPEND ON THIS!
22
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
23
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
– 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
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
31
Program Example: Grading Program
• Grade records for a class can be stored in a
two-dimensional 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 a student
• The second array index refers to a quiz number
int a[4][5];
38
Lecture 4
4.2 Pointers
39
Sorting & Searching
4.1
40
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
41
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
42
43
44
Program Example:
Sorting an Array
• Sorting a list of values is 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
45
Program Example:
The Selection Sort Algorithm
• When the sort is complete, the elements of the
array are ordered such that
– …ascending order
2. Place this value in a[0], and place the value that was in a[0]
in the location where the smallest was found
51
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
52
Pointers Tell
Where To Find A Variable
53
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
54
Lets 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 ]
55
Multiple Pointer Declarations
• To declare multiple pointers in a statement,
use
the asterisk before each pointer variable
– Example:
int *p1, *p2, v1, v2;
56
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: p1 = &v1;
p1 is now a pointer to v1
v1 can be called v1 or "the variable pointed to by
p1"
57
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 dereferenced
58
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;
output:
42
42
59
Pointer Assignment
• The assignment operator = is used to assign
the value of one pointer to another
– Example: If p1 still points to v1 (previous slide)
then
p2 = p1;
60
Caution! Pointer Assignments
• Some care is required making assignments to
pointer variables
– p1= p3; // changes the location that p1 "points" to
61
62
More example:
#include <iostream>
using namespace std; output:
int main() { 10 20 10 20
Must have int x=10, y=20;
11 24 11 24
bracket, int* p1;
11 24 24 24
without them it int* p2;
p1 = &x; 11 24 24 11
means *(p1++)
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;
}
63
Pointers and Constants
Pointer to Constant
64
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 *] can NOT be used
*p = 10; to MODIFY the value it is
z = 10; pointing to.
65
Constant Pointer
p has a type [int * const]
meaning that it is a constant
pointer,
int m,n; the value it is pointing to is not
int * const p = &n; constant,
but p itself is a constant and can
*p = 10;
not be changed
n = 5;
p = &m;
p must be initialized (just as any
constant variable must be
initialized)
66
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.
67
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 :
69
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]
70
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 anyplace an integer variable can
cin >> *p1;
*p1 = *p1 + 7;
71
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)
72
Slide 9- 73
74
new and Class Types
• Using operator new with class types calls
a constructor as well as allocating memory
– If MyType is a class type, then
78
79
Automatic Variables
• Variables declared in a function are created by
81
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;
82
Defining Pointer Types
• To avoid mistakes using pointers, define a
pointer type name
– Example: typedef int* IntPtr;
is equivalent to
int *p;
83
Multiple Declarations Again
• Using our new pointer type defined as
typedef int* IntPtr;
// variables
84
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);
85
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?
86
C++ Fundamentals -- End
87