# C++ Notes: Example - readArray

Here is a function to read from cin into an array, written in three different styles.

## 1. Using reference parameter and array

This simple solution uses the array size to avoid a buffer overflow, but silently ignoring the error of too much input is not good. Throwing an exception would be a more robust solution.

    void readArray(int a[], int& n, int maxsize) {
        // function:
        //    Reads from cin until array full or to an EOF.
        // parameters:
        //    a       out  array destination of values.
        //    n       out  number of values in a, a[0]..a[n-1]
        //    maxsize in   maximum number of elements that can fit in a
        // returns:
        //   nothing

        n = 0;  // start with an empty array.
        while (n < maxsize  &&  cin >> a[n]) {
            n++;
        }
        return;
    }

## 2. Using pointer for array and reference parameter for size

Rewriting the above using the equivalent `int*` instead of the array type.

    void readArray(int* a, int& n, int maxsize) {
        n = 0;  // start with an empty array.
        int* limit = a + maxsize;  // address after last element
        while (a < limit  &&  cin >> *a) {
            a++;
            n++;
        }
        return;
    }

As before, a call would look like

       readArray(temps, size, 1000);

## 3. Using all pointers

Changing the reference parameter to a pointer looks like this:

    void readArray(int* a, int* n, int maxsize) {
        *n = 0;  // start with an empty array.
        int* limit = a + maxsize;  // address after last element
        while (a < limit  &&  cin >> *a) {
            a++;
            *n = *n + 1;
        }
        return;
    }

Because the size parameter is a pointer, the call must be written as

    readArray(temps, &size, 1000);