Can a user determine the size of an array through the programme?

For example,
At the beginning of the programme it will ask the user 'How many students' exams grades would you like to process today'
Therefore create the array to be of the size that the user has entered.

I know that if we use MAX_SIZE with a const all we have to do is change one number at the top from a code, but from a users point of view that is not really user friendly!


You mean dynamic arrays? Sure it's possible:

int howmany = 0;
    cout << "how many?";
    cin >> howmany;
    int *arr = new int[howmany];
    // do stuff
    delete[] arr;

but if you don't want to worry about memory management, you could also have a look at vectors:

#include <vector>


vector<int> arr;

cout << "Arr size is now " << arr.size() << " elements:\n";
for (int i = 0; i < arr.size(); i++)
    cout << arr[i] << "\n";

if i use dynamic array

what do i put when i declare the variables:

and in normal use what do i put:

read my first example.

You can acces the array in the same way you would with a static-array.
Let's say that 'howmany == 4'
That will create an array with 4 elements (0-3):

int howmany = 0;
    cout << "how many?"; // type 4
    cin >> howmany;
    int *arr = new int[howmany];

    arr[0] = 2;
    arr[1] = 452;
    //etc, but do not go past arr[3]! if you typed in 4

    cout << arr[0] << arr[1];
    delete[] arr;

Just make sure that you never (ever) write or read memory that is out of bounds! That's why I recommend my second example

This article has been dead for over six months. Start a new discussion instead.