-5

please can someone tell me why these code, when run prints 1 instead of 3.5 to the console. it implemnts passing an array to a function, to calculate average of the array elements. i used the sizeof(array)/sizeof(int) as array length

#include "stdafx.h"

#include <iostream>

// function avg, to calculate average of an integer array.
double avg(int iArray[])
{
    // initialize variable y to calculate sum
    // initialize variable to calculate length of array    
    int y{}, z = sizeof(iArray) / sizeof(int);

    // loop over array elements
    for (int i{}; i < z; i++)
    {
        y += iArray[i];
    }

    // return average to caller
    return ((double)y) / z;
}

int main()
{
    using namespace std;

    // initialize array.
    int iArray[] = { 1, 2, 3, 4, 5, 6 };

    // call avg function, and assign return value to variable z.
    double z = avg(iArray);

    // print average to console
    cout << z << endl;

    return 0;
}
m.s.
  • 16,063
  • 7
  • 53
  • 88
Evan
  • 75
  • 1
  • 8

1 Answers1

0
double avg(int iArray[])
{
    int y{}, z = sizeof(iArray) / sizeof(int);

is equivalent to

double avg(int* iArray)
{
    int y{}, z = sizeof(int*) / sizeof(int);

You need to pass the size of the array from main.

double avg(int iArray[], int z)
{
    // initialize variable y to calculate sum
    int y{};

    // loop over array elements
    for (int i{}; i < z; i++)
    {
        y += iArray[i];
    }

    // return average to caller
    return ((double)y) / z;
}

and in main:

double z = avg(iArray, sizeof(iArray)/sizeof(iArray[0]);
R Sahu
  • 204,454
  • 14
  • 159
  • 270