Topics covered on Monday, 2010-08-23
Using Pointers
Display characters in string, Version 1
1 //
2 // pointer1.cpp
3 //
4 // Print out the elements of an array, one per line.
5 // Use array indices.
6 // Copyright 2010, Raj Mathur
7 //
8 #include <iostream>
9 #include <cstdlib>
10
11 using namespace std;
12
13 int main( int argc, char *argv[] )
14 {
15 char
16 r[] = "this is the 0th house that jack built this is the malt that lay in the house that jack built etc. etc.";
17 for( int i = 0; r[i] != '\000'; i++ ) // Explicitely check for NUL byte
18 {
19 cout << r[i] << endl;
20 }
21 exit(0);
22 }
This program traverses the array
r in the normal fashion, by selecting each of its elements (characters) one by one using an index (
i).
Display characters in string, Version 2
1 //
2 // pointer2.cpp
3 //
4 // Print out the elements of an array, one per line.
5 // Use array indices. Implicitly check for NUL.
6 // Copyright 2010, Raj Mathur
7 //
8 #include <iostream>
9 #include <cstdlib>
10
11 using namespace std;
12
13 int main( int argc, char *argv[] )
14 {
15 char
16 r[] = "this is the 0th ->\000<- house that jack built this is the malt that lay in the house that jack built etc. etc.";
17 for( int i = 0; r[i]; i++ )
18 {
19 cout << r[i] << endl;
20 }
21 exit(0);
22 }
This version of the program does the same as the one above. However, since any non-zero value in C++ is considered
true and any zero value is considered
false, it doesn't bother checking explicitly whether the char element is zero or not.
The program also demonstrates the use of the
escape character,
\, in strings.
\000 is the NUL byte, i.e. a byte with value zero.
Display characters in string, Version 3
1 //
2 // pointer3.cpp
3 //
4 // Print out the elements of an array, one per line.
5 // Use a char pointer to traverse the array.
6 // Display the pointer values while printing to demonstrate logic flow.
7 // Copyright 2010, Raj Mathur
8 //
9 #include <iostream>
10 #include <cstdlib>
11
12 using namespace std;
13
14 int main( int argc, char *argv[] )
15 {
16 char
17 r[] = "this is the house that jack built.";
18 cout << "r is " << (unsigned int)r << endl;
19 char
20 *cp;
21 for( cp = r; *cp; cp++ )
22 {
23 cout << "cp is " << (unsigned int)cp << endl;
24 cout << *cp << endl;
25 }
26 exit(0);
27 }
The third version of the program uses a
pointer to character,
cp, to traverse the array
r.
cp starts off pointing to the first element of the array
r and keeps getting incremented each time through the loop so that it points to each subsequent character.
The program also prints out the values of
r and
cp to demonstrate the actual values they take during the execution.
Assignment 1
Create a program with two character arrays,
a1 and
a2. Set
a1 to the string
"copyme". Now use 2 pointers to char to copy the contents of
a1 into
a2.