Re: [C] determining size of an array in a function

From: pete (pfiland_at_mindspring.com)
Date: 09/18/04


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


Relevant Pages

  • Re: [C] determining size of an array in a function
    ... > The function needs to know the size of the array, ... the function only receives a pointer to the array's ... and you can't determine the size of the array from that. ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Why not call Thread.join?
    ... before any of the threads finished sleeping for 5 seconds. ... statement will see an undetermined intermediate view of the array). ... to execute, and possibly terminate. ...
    (comp.lang.ruby)
  • Re: random array elements and speed
    ... # need int here since we are checking for dups and floats won't work ... case I were to need more elements than those in the returned array. ... that could theoretiocally never terminate. ... the original array, but small's a relative term and the expected speed ...
    (comp.lang.perl.misc)
  • [C] determining size of an array in a function
    ... My program performs several statistical tests on a list of ... int listsize = sizeof/ sizeof; ... The function needs to know the size of the array, ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Improvement hints for poor mapping description
    ... I wanna describe some mapping of a function that takes 3 inputs a,b,c ... I tried to use the mapsto command to an ... array but it doesnt really look good. ... they do not terminate them. ...
    (comp.text.tex)