1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
// Program to read words and print in reverse order.
// Illustrates use of new keyword to dynamically allocate
// space for each of the strings that are read in.
// If the variation in "word" size is very large,
// dynamic allocation is the only reasonable solution.
// What this program doesn't do, but should, is reallocate
// the word and allwords arrays to make them expand
// as needed. Currently it is subject to buffer overflows.
// Fred Swartz 2001-11-08
#include <iostream>
using namespace std;
int main() {
char *wordList[1000]; // array of POINTERS to char strings
char inputBuffer[1000]; // input area for longest possible word.
int n = 0; // count of number of words and index.
//--- read words/tokens from input stream
while (cin >> inputBuffer) {
int len = strlen(inputBuffer); // length of word just read
wordList[n] = new char[len+1]; // allocate space for word
strcpy(wordList[n], inputBuffer); // copy word to new space
n++;
}
cout << "Hello?" << endl; // Hmmm, this line disappears.
cout << "Number of words = " << n << endl;
// --- Write the words in reverse order.
for (int i=n-1; i>=0; i--) {
cout << wordList[i] << endl; // print the word
// Delete dynamically allocated space when no longer needed.
// The pointer is set to NULL to prevent accidental use of it.
// This isn't necessary here because the program terminates.
// But it's good practice, and makes bug detection easier.
delete [] wordList[i]; // free space
wordList[i] = NULL; // remove pointer
}
return 0;
}//end main |