-2

I want to pass an array to a function. When investigating in debug mode, I detected that only the first element of the array in the main part is passed to the function. I have no clue why this is or what to correct to pass the full array. The function code works fine when in moved in the main.

double avg(int arr[]) {
    int ArrayLength = sizeof(arr) / sizeof(arr[0]);
    int sum = 0; 
    double average = 0;
    cout << ArrayLength << endl;
    for (int i = 0; i < ArrayLength; i++) {
        sum += arr[i];
    }
    return double(sum)/ArrayLength ;
};

int main()
{
    int Arr[] = { 2,4,6,8,10,12,20 };
    cout << "Average value is: " << avg(Arr) << endl;
    return 0;
}

1 Answers1

0

You're not declaring the size of the array, so sizeof is returning the size of a single element. All the data will be there in memory though, but beyond the sizeof point.

Pass in a length (normal), or fix the size in the declaration

James
  • 224
  • 2
  • 13