------------------------------------------------------------------------------
MC logo
Dynamic Array Allocation
[^] Code Examples
------------------------------------------------------------------------------
<<How Big Do You Want That Array, Sir? dynarr3.cc Variable-Sized Arrays>>
#include <iostream>

using namespace std;

// Read in the indicated number of numbers, then print them backwards.
void rne(int arr[], int size)
{
        for(int i = 0; i < size; ++i)
                cin >> arr[i];

        cout << "----------------------------------------------------" << endl;
        for(int i = size-1; i >= 0; --i)
                cout << arr[i] << " ";
        cout << "\n----------------------------------------------------" 
             << endl;

}

main()
{
        // Fixed size.
        int fred[5];
        rne(fred, 5);

        // Allocate with malloc (C style).
        int size;
        cin >> size;
        int *arr = (int *)malloc(size * sizeof(int));
        rne(arr, size);
        free(arr);

        // Allocate with new (C++ style).
        cin >> size;
        arr = new int[size];
        rne(arr, size);
        delete [] arr;
}
<<How Big Do You Want That Array, Sir? Variable-Sized Arrays>>