0% found this document useful (0 votes)
13 views87 pages

Lec03-04 (Topic 2 Arrays and Pointers)

Uploaded by

Abc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views87 pages

Lec03-04 (Topic 2 Arrays and Pointers)

Uploaded by

Abc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 87

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
Array Syntax

4
Declaring an Array
• An array, named score, containing five variables
of type int can be declared as
int score[ 5 ];

• This is like declaring 5 variables of type int:


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

• The value in brackets is called


– A subscript
– An index
5
The Array Variables
• The variables making up the array are referred to
as
– Indexed variables
– Subscripted variables
– Elements of the array

• 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
6
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
7
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
– The value in the [ ]'s can be any expression that evaluates
to one of the integers 0 to (size -1)
8
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

9
Loops And Arrays
• for-loops are commonly used to step through
arrays First index is 0 Last index is (size – 1)

– Example: for (int i = 0; i < 5; i++)


{
cout << score[i] << " off by "
<< (max – score[i]) << endl;
}
could display the difference between each score
and the maximum score stored in an array
10
Slide 7- 11
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

12
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


13
Array Declaration Syntax
• To declare an array, use the syntax:

– Type_Name Array_Name[Declared_Size];

– Type_Name can be any type


– Declared_Size can be a constant to make your
program more versatile

• Once declared, the array consists of the indexed


variables:
Array_Name[0] to Array_Name[Declared_Size -1]
14
Computer Memory
• 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

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;

• 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!
19
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;
20
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

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

• 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

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

– 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
24
25
Constants as Arguments
• During the declaration of the array, MAX_SIZE
is used to determine the array size

– Can't the value of MAX_SIZE be used directly


without making it an argument?

• 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
Knowledge Check
• Can you

– Describe the difference between a[4] and int 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?

abcd should be output as dcba

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


27
28
Two-dimensional arrays
3.2

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

– Each index in enclosed in its own brackets

– Page can be visualized as an array of


30 rows and 100 columns
30
Index Values of page
• The indexed variables for 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 actually an array of size 30


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

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

• Since student and quiz numbers start with one,


we subtract one to obtain the correct index
32
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
33
34
35
36
37
Knowledge Check
• Can you

– Write code that will fill the array a(declared


below) with numbers typed at the keyboard? The
numbers will be input five per line, on four
lines.

int a[4][5];

38
Lecture 4

Arrays and Pointers


4.1 Sorting & Searching

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

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


46
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 swap it


with the value currently in a[1]

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


sorted
47
Slide 7- 48
49
50
Pointers
4.2

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

• 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

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 ]

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 store 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

55
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

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;

causes *p2, *p1, and v1 all to name


the same variable

– What is the value of pointers?

60
Caution! Pointer Assignments
• Some care is required making assignments to
pointer variables
– p1= p3; // changes the location that p1 "points" to

– *p1 = *p3; // changes the value at 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;
}

p1 now also points to y.

63
Pointers and Constants
Pointer to Constant

const int n = 3; n is constant


int* p;
p = &n;

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


type [const int].
INVALID

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.

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

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)

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


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

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

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.
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

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
now: p[0] is equivalent to n[2], [ int* ] n[4]
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 ]
68
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".

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]

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


of the array) in the "simulated" array.

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

MyType *myPtr; // creates a pointer to a


// variable of type MyType
myPtr = new MyType;
// calls the default constructor

myPtr = new MyType (32.0, 17);


// calls Mytype(double, int);
75
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
76
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
77
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
disasterous

78
79
Automatic Variables
• Variables declared in a function are created by

C++ and destroyed when the function ends


– These are called automatic variables because their
creation and destruction is controlled
automatically
• The programmer manually controls creation
and destruction of pointer variables with
operators new and delete
80
Global Variables
• Variables declared outside any function
definition are global variables
– Global variables are available to all parts of a
program
– Global variables are not generally used

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;

• Known_Type_Definition can be any type

82
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;

83
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
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);

is less confusing than

void sample_function( int*& 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

Slides adapted from


Walter Savitch, “Problem
solving with C++”

87

You might also like