Handout 12a
More Strings
1 #include <iostream.h>
2 #include <string.h>
3
4 // some character string examples
5
6 int main() {
7
8 // a character string
9 char word_a[] = "this is a word";
10
11 // an array of character strings
12 char word_b[3][10] = {"123","1234","12345"};
13
14 // a simple character pointer
15 char * ptr_a = NULL;
16
17 // an array of character pointers (initialized to NULL)
18 char * ptr_b[3] = {NULL, NULL, NULL};
19
20 // an array of character pointers that also allocates storage
21 // for character strings
22 char * ptr_c[3] = {"first", "second", "third"};
23
24 // an array of character pointers that also allocates storage
25 // for one of the pointers, all other pointers are uninitialized
26 // and no storage is associated with them
27 char * ptr_d[3] = {"storage is allocated for ptr_d[0] only"};
28
29 cout << strlen(word_a) << endl; // treats array name as a pointer
30 // outputs 14
31
32 cout << strlen(word_b[0]) << endl; // treats word_b[0] as a pointer
33 // outputs 3
34
35 ptr_b[0] = ptr_c[0]; // have both these pointers point at the same place
36
37 cout << ptr_b[0] << endl; // outputs "first";
38
39 cout << strlen(ptr_d[0]) << endl; // treats ptr_d[0] as a pointer
40 // outputs 38
41
42 cout << word_b << endl; // outputs the starting address of word_b
43
44 cout << word_b[0] << endl; // outputs the string "123"
45
46 cout << word_b[0][0] << endl; // outputs the character '1'
47
48 }
Program Output
14
3
first
38
0x0012FF50
123
1
source code is available here.