Partially filled array question

If I create an int array with size ten and I want the user to input at most ten numbers, how can I change the array's size so that it equals the number of inputs?
Sounds like you need a vector.

If you can't use vectors, you can make an array of CAPACITY 10, and call the SIZE the number of numbers in the array.
Last edited on
So if I set a size variable to 10 and created an array int a[size], I can later change size to the number of inputs, and the array's size will change to that number as well right?
So if I set a size variable to 10 and created an array int a[size], I can later change size to the number of inputs, and the array's size will change to that number as well right?

In c++ an array size is a constant, not a variable.

You might write
 
    int arr[10];
though it is better practice to write
1
2
    const int size = 10;
    int arr[size];
In both cases, the size of the array is a constant which is known at compile-time. It cannot be later changed.

What you might do instead is to use a separate variable such as int count = 0; to keep track of how many elements are currently in use. Example,
1
2
3
4
5
6
    const int size = 10;
    int arr[size];
    arr[0] = 2;
    arr[1] = 3;
    arr[2] = 5;
    int count = 3;
Note, count may be changed (within the constraints of the array size) but size is fixed and cannot be changed.

Using vectors, things become a lot easier, as it will automatically keep track of its own size - and that size can be changed as necessary.
1
2
3
4
    vector<int> vec;
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(5);

You can find the size of the vector with vec.size()

Last edited on
Topic archived. No new replies allowed.