Transcript Document

Arrays
We have already used a numeric array (our decimal to binary conversion)
All arrays contain elements of the same basic data type (regardless of basic data type) and
must be stored at contiguous memory locations. The lowest address corresponds to the
first element and the highest address to the last element.
Notice that the first element in C/C++ always has the subscript (index value) zero
“In mathematics and computer programming, Index notation is used to specify the elements
of an array of numbers” http://en.wikipedia.org/wiki/Index_notation
Why must all of the elements in an Array be of the same basic data type??
Why must they be stored in contiguous memory??
Why must the first element in the array have the subscript zero??
Arrays
Consider the following array declaration
short primenos {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53};
The array has 16 elements and will be stored as
Offset/Index
0
2
1
3
2
5
3
7
4
11
5
13
6
17
7
19
8
23
9
29
10
31
11
37
12
41
13
43
14
47
15
53
We know that each element requires 16-bits (2 bytes) of storage. Therefore:
•
If the base address of array primenos is 1,000 the address of each element in the array
is 1,000 + (2 * offset/index)
Offset
0
1
2
3
4
5
6
7
8
9
10
11
12
Address
1,000
1,002
1,004
1,006
1,008
1,010
1,012
1,014
1,016
1,018
1,020
1,022
1,024
Notice also that the first offset is always 0 (which is why our formula works)
How do we know this??
Arrays and pointers
Enter, compile and run the following code
#include "stdafx.h"
#include <iostream>
using namespace std;
void main()
{
int primenos[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53};
int i;
int * mypointer;
mypointer = &primenos[0];
printf("The base address is%ld\n\n", mypointer);
for (i=0; i <15; i++)
{
cout << "the value at primenos[" << i << "] is " << primenos[i];
mypointer = &primenos[i];
printf(" It is stored at %ld\n", mypointer);
}
}
Arrays
Your output should look like
Arrays and Pointers
We also previously noted that we could pass an array to another function, but we could pass a pointer
•
Enter, compile and execute the following code
#include "stdafx.h"
#include <iostream>
using namespace std;
// function prototype for printarray
void printarray(int nvals, int *parray [ ]);
void main()
{
// declare and initialize the array variable
int i,*arrayPtr[7], primenos[7]={2,3,5,7,11,13,17};
//Store the array addresses
for(i=0; i<7; i++)
arrayPtr[i] = &primenos[i];
// call to function printarray, pass along the pointer to the 1st array element
printarray(7, arrayPtr);
}
void printarray(int nvals, int *parray [ ])
{
short count;
for (count=0; count < nvals; count++)
{
cout << "the value at offset [" << count << "] is " << *parray [count];
printf(" It is stored at %ld\n", &parray[count]);
}
}
Arrays and Pointers
Your output should appear as follows:
Multidimensional Arrays
Arrays of course can be multidimensional (think spreadsheet)
• Consider a 2-dimensional array, where the first column holds a prime
number, and the second column contains the square of the first
column:
Offset
0
1
2
3
4
5
6
7
0
2
3
5
7
11
13
17
19
1
4
9
25
49
121
169
289
361
Arrays
Enter, compile and run the following code
#include <iostream>
using namespace std;
void main()
{
int i, primenos[5][2] = {{2,1}, {3,1}, {5,1}, {7,1}, {11,1}};
for (i=0; i <5; i++)
{
primenos[i][1] = primenos[i][0] * primenos[i][0];
cout << "primenos[" << i << "][0] = " << primenos[i][0] << " at address "<< &primenos[i][0] << endl;
cout << "primenos[" << i << "][1] = " << primenos[i][1] << " at address "<< &primenos[i][1] << endl;
}
}
The output should
appear as:
Arrays
The addresses given are in Hexadecimal
Decimal 0
Hex
0
1
1
2
2
The corresponding
decimal values are:
Hex
2FF8D8
2FF8DC
2FF8E0
2FF8E4
2FF8E8
2FF8EC
2FF8F0
2FF8F4
2FF8F8
2FF8FC
Dec.
3143896
3143900
3143904
3143908
3143912
3143916
3143920
3143924
3143928
3143932
3
3
4
4
5
5
6
6
7
7
8
8
9 10 11 12 13 14 15
9 A B C D E F
The array elements would be stored at:
Offsets
0
1
2
3
4
0
3143896
3143904
3143912
3143920
3143928
1
3143900
3143908
3143916
3143924
3143932
Strings
• Strings are arrays of data type char, but are treated slightly differently.
Consider the following sentence:
The quality of mercy is not strained; It droppeth as the gentle rain from
heaven upon the place beneath.
Quickly – How many characters are in the sentence (including spaces and the semicolon and the period)??
(There are 107 – I think)
• The point is that how many characters a string contains is not
something we are interested in.
(We are concerned only about where it begins and where it ends)
• The beginning is easy: as with any array, it is the base address of the
array
(We will talk about where it ends in a little while)
Strings
• Let’s first do it the hard way. Enter the following code:
#include "stdafx.h"
#include <iostream>
using namespace std;
void main()
{
short i;
char string1[11];
string1[0] ='H';
string1[1] ='e';
string1[2] ='l';
string1[3] ='l';
string1[4] ='o';
string1[5] =' ';
string1[6] ='W';
string1[7] ='o';
string1[8] ='r';
string1[9] ='l';
string1[10] ='d';
for (i=0; i<11; i++)
cout << string1[i];
cout << endl;
}
Strings
• Not surprisingly, the output is:
• This program works because we knew exactly how many characters
were in this string (11)
• However, we initially stated that we didn’t want to constantly count all
of the characters in a string.
Strings
The null character '\0' is used to terminate C strings
Let’s modify our previous code
Changes??
void main()
{
char string1[12];
string1[0] ='H';
string1[1] ='e';
string1[2] ='l';
string1[3] ='l';
string1[4] ='o';
string1[5] =' ';
string1[6] ='W';
string1[7] ='o';
string1[8] ='r';
string1[9] ='l';
string1[10] ='d';
string1[11] ='\0';
printf("%s\n",string1);
}
1 additional character needed (‘\0’)
Add the null character (‘\0’)
Use the %s printf token
(The output will look the same)
Strings
What happens if we forget to add the null character???
Try it. Delete the string1[11] ='\0'; command line (or comment it out)
Your output should appear something like:
Why???
When we first started talking about strings, we said we know where the
string starts (at the base address of the string) AND where it ends
• Without the null character, we don’t know where it ends
Strings
Fortunately for us, there are easier ways to enter and print out strings.
#include "stdafx.h"
#include <iostream>
using namespace std;
void main()
{
char string1[] = “Hello World!!";
puts (string1);
// You could use the command: cout << string1 << endl;
}
(The output will look the same – Try it for yourself)
Strings
Because we can perform a lot of different operations on strings there
are a number of functions available to us
(See http://www.cplusplus.com/reference/cstring/ for a more complete list)
Let’s look at some of the more common ones
(You must use the precompiler header: #include <string>)
Enter the following code:
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
void main()
{
char string[] = "The quality of mercy is not strained; It droppeth as the gentle rain from heaven upon the
place beneath.";
int schars = strlen(string);
puts (string);
cout << "There are " << schars <<" Characters in the string\n";
}
Strings
The output would appear as:
Another commonly used function is strcmp (which compares 2 strings
to find out if they are equal (or not)).
Consider the two strings:
char string1[] = “Apple“, string2[] = “Apple“;
To compare the strings, we need to compare them letter by letter in a loop
Consider the programming logic on the following slide
Strings
Pass Offset Char1 Char2 Equal?
1
0
A
A
Y
2
1
p
p
Y
3
2
p
p
Y
4
3
l
l
Y
5
4
e
e
Y
6
5
\0
s
N
Using function strcmp makes our life much easier. Consider (enter,
compile and run) the following code:
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
void main()
{
char string1[] = "Apple", string2[] = "Apples";
cout << "The strings " << string1 << " and " << string2 << " are " << strcmp(string1, string2) << endl;
}
Strings
The output would appear as:
Typically, most T/F functions return the value 0 (zero) if the result is
true.
In this function (and others) if the first string (address) is less than
(alphabetically) the second, the function returns the value -1 (i.e., they
were the same until the -1 comparisons to go)
We could clean up the program a little with the following code
Strings
void main()
{
char string1[] = "Apple", string2[] = "Apples";
cout << "The strings " << string1 << " and " << string2 << " are ";
if (strcmp (string1,string2) == 0)
cout << "Equal";
else
cout << "Not equal";
cout << endl;
}
The output would appear as:
Strings
A similar problem occurs when we try to copy one string to another.
Consider the variable declarations:
char string1[] = "I Love C++", string2[];
Where we want to copy the contents of string1 into string2
We know these have to be copied character by character:
string1[]
string2[]
I
L
o
v
e
C
+
+
\0
73
32
76 111 118 101 32
67
43
43
0
73
32
76 111 118 101 32
67
34
34
34
Strings
Strings
Strings
Strings
Strings
Strings
Strings
Strings
Strings
Strings