Re: [C] determining size of an array in a function
From: pete (pfiland_at_mindspring.com)
Date: 09/18/04
- Next message: Jerry Coffin: "Re: google "top coder" contest = stacked against C++ coders"
- Previous message: pete: "Re: Tips on gaining proficiency in C"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 18 Sep 2004 15:38:01 GMT
Marlene Stebbins wrote:
>
> My program performs several statistical tests on a list of
> numbers. For example:
>
> double stdev(double *arglist, int listsize); /* prototype */
> double data[] = {76.9, 45.5, 32, 99.6, 12, 56.2, 79.9, 81};
> int listsize = sizeof(data) / sizeof(*data);
> double s = stdev(data, listsize);
>
> The function needs to know the size of the array, so I am passing
> it as an argument. I am wondering if there is any way for the
> size of the the array to be determined in the function -- without
> a global variable or a kludge -- so I can eliminate the 2nd
> argument in the call to stdev(). I think there is no elegant way
> to do this, but I thought I would ask the experts.
It may be possible to terminate the array with a value
that doesn't occur anywhere else in the array.
If it's not possible for any other array element to have a value of
HUGE_VAL (from math.h) for example,
then you might be able to terminate the array with that value.
#include <stdio.h>
#include <math.h>
double avg(double *);
int main(void)
{
double data[] = {76.9,45.5,32,99.6,12,56.2,79.9,81, HUGE_VAL};
double s = avg(data);
printf("The data average is %f.\n", s);
return 0;
}
double avg(double *data)
{
double sum;
size_t count;
for (sum = count = 0; *data != HUGE_VAL; ++count) {
sum += *data++;
}
return sum / count;
}
-- pete
- Next message: Jerry Coffin: "Re: google "top coder" contest = stacked against C++ coders"
- Previous message: pete: "Re: Tips on gaining proficiency in C"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|