codegeek123
codegeek123

Reputation: 43

test file to library file, array not being read in properly issue in c

So my c code is not properly reading in the array being passed in to the library function I created. It for some reason is outputting size 4, when it is size 10, etc. Please help me make this work. The library is included in the file header.

int main()
{
// data of array
double input[] = {30.0, 90.0, 100.0, 84.0, 72.0, 40.0, 34.0, 91.0, 80.0, 62.0};
// size of array
int size = sizeof(input)/sizeof(double);

// getting information from library based on data of array
printf("The mean is: %.2f", calculateMean(size, input));
}

// This is the library //returns the mean of data

double calculateMean(int totnum, double data[])
{

double total = 0;
int size = sizeof(data)/sizeof(double);


for(int i=0; i<size; i++)
{
    total += data[i];

}
return (double)total/size;
}

Upvotes: 1

Views: 27

Answers (2)

ashiquzzaman33
ashiquzzaman33

Reputation: 5741

In calculateMean you use

int size = sizeof(data)/sizeof(double);

to get the size of data. But the array is passed to function as a pointer. So your size may be initialize to 0 (As in most platforms sizeof(double) > sizeof(double*))

You pass totnum to the function but don't use it. Using it you can solve the problem

double calculateMean(int totnum, double data[])
{

    double total = 0;
    for(int i=0; i<totnum; i++)
    {
        total += data[i];

    }
    return (double)total/totnum;
}

Upvotes: 1

ameyCU
ameyCU

Reputation: 16607

In your functin double calculateMean(int totnum, double data[]) you dont need to calculate size again as you pass totnum use it instead of size -

int size = sizeof(data)/sizeof(double);   // useless in function.

This should not be done in any function when passing array as it is computed as -

sizeof(double *)/sizeof(double)  // computing size uncorrect.

Upvotes: 0

Related Questions