C++: Containers: Example 1 Using Array
One of three contrasting examples of solving the problem with increasingly
powerful tools:
using arrays, then
vectors, then
stacks.
// Read words and print them in reverse order.
// Variation 1: Fixed array sizes, use new to copy word.
// Fred Swartz 2001-11-08, 2001-12-04
#include <iostream> // for cin, cout
#include <cstring> // for strlen, strcpy
using namespace std;
int main() {
char *allwords[1000]; // array of POINTERS to char strings
char word[500]; // input buffer for longest possible word.
int n = 0; // count of number of words.
// read words/tokens from input stream
while (cin >> word) {
allwords[n] = new char[strlen(word)+1]; // allocate space
strcpy(allwords[n], word); // copy word to new space
n++;
}
cout << "Number of words = " << n << endl;
// write out all the words in reverse order.
// The dynamically allocated space is freed after the word
// is printed, and the pointer is set to NULL. This isn't
// necessary here because the program immediately terminates,
// but it's a good, safe practice.
for (int i=n-1; i>=0; i--) {
cout << allwords[i] << endl; // print the word
delete [] allwords[i]; // free space
allwords[i] = NULL; // remove pointer
}
return 0;
}//end main
The big problem with this program is that is is subject to buffer overflow
bugs -- words larger than 499 characters or more than 1000 words will
simply overflow the arrays until something so serious happens that the
program can't continue running. Let's hope it didn't overwrite one of you
open output file buffers, for example.