# C++ Notes: Example - Words in Reverse Order - Expanding Array

      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
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
    // arrayptr/reverse-word-order-exp.cpp - Reverse words. Use expanding array.
    // Fred Swartz - 2004-02-02

    #include <string>
    #include <iostream>
    using namespace std;

    //============================================= prototypes
    void rev(string* first, int size);

    //=================================================== main
    int main() {
        int maxSize = 10;
        string* word = new string[maxSize];
        int n;          // number of words

        //--- Read words into an array,
        n = 0;
        while (cin >> word[n]) {
            n++;
            if (n >= maxSize) {
                maxSize = maxSize * 2;       // Double the previous size.
                cerr << "Expanding array to " << maxSize << endl;
                string* temp = new string[maxSize]; // Allocate bigger array.
                for (int i=0; i<n; i++) {
                    temp[i] = word[i];       // Copy old array to new array.
                }
                delete [] word;              // Free old array memory.
                word = temp;                 // Now a points to new arra
            }
        }

        //--- Reverse order of the array elements.
        rev(word, n);

        //--- Print the array
        for (int i=0; i<n; i++) {
            cout << word[i] << endl;
        }
        system("PAUSE"); // NON-PORTABLE to keep Dev-c++ window open.
    }

    //==================================================== rev
    void rev(string* first, int size) {
        string* last = first + (size-1); // ptr to last elem

        while (first < last) {
            string temp;
            temp   = *first;
            *first = *last;
            *last  = temp;

            first++;
            last--;
        }
    }