-5

I'm facing some problems with my code in C++. I would like to know how can I discover the amount of elements in an array. Follow the code:

#include <iostream>
#include <cstdlib>

using namespace std;

int avg(int numbers[]){
    int amount; // The problem is in. How can I discover the amount of elements in an array?

    int sum = 0;
    for(int i = 0; i < amount; i++){
        sum += numbers[i];
    }

    return sum / amount;
}

int main(){
    int q;
    cout << "Type number of integers:" << endl;
    cin >> q;

    int numbers[q];

    for(int i = 0; i < q; i++){
        cout << "Type an integer value for number " << i+1 << ":" << endl;
        cin >> numbers[i];
    }

    cout << "The average is " << avg(numbers) << endl;

    return 0;
}
Luiza
  • 1
  • 1
  • 2
    This `int numbers[q];` is not valid C++, so your question is moot. Simply put, don't write code like that - use a std::vector. –  Nov 15 '18 at 18:22
  • To follow up on that, you should either declare your array to be "large enough" at compile time (in which case you know how large it is already) or dynamically allocate more memory as needed (you'll again know when you size or re-size it)! Further, arrays are often a poor choice and you should use a more appropriate datatype that already knows its own size. – ti7 Nov 15 '18 at 18:24
  • 2
    use std::vector – pm100 Nov 15 '18 at 18:35

1 Answers1

1

The standard array in C++ doesn't contain a way to access the size of the array, the best way to track this is to have an integer that is updated with the size of the array or to try using std::array and then use the .size() method.

In your example you are using a fixed size array anyway so you may want to store the q value as a member variable and that contains the array size. Notice that in your example the code will not work as q is not a constant integer. To declare an array without a constant integer you will need to use a pointer to the first element of the array ie: int* numbers = new int[q];.

Will Anderson
  • 113
  • 1
  • 14
  • An array's size is encoded in the type, standard arrays are aware of their size. It's only when they decay to raw pointers that the information is lost. And array type function parameters are just window dressing for raw arrays. – François Andrieux Nov 15 '18 at 18:25
  • *"C++ doesn't contain a way to access the size of the array*" There is `std::size` and the old `sizeof array / sizeof array[]` trick. You can't get a size of an array when you only have a pointer to the first element. – HolyBlackCat Nov 15 '18 at 18:25
  • @HolyBlackCat if it's not a pointer to the first element then the size will be fixed anyway – Will Anderson Nov 15 '18 at 18:27