#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    5
    Rep Power
    0

    passing an array of structures to a function


    I am relatively new to C and I am having a problem passing an array of structures to a function. Here is how I define the the structure,

    typedef struct {
    double CL;
    double CP;
    } TypeMu;

    I then define the array as,

    TypeMu Mu[MAX_ARRAY];

    Now I am not sure how to go from here to pass it to a function.

    I have tried passing the array itself but that does not seem to workout correctly. I would appreciate any help any one could give me. Thanks.
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,088
    Rep Power
    2222
    A basic fact of life in C is that an array name is equivalent to a pointer. Therefore, there are two ways that you can choose from that are identical:
    Code:
    void foobar1(TypeMu mu[]);
    void foobar2(TypeMu *mu);
    
    int main(void)
    {
        /* the actual passing of the argument is the same syntax in both cases */
        foobar1(Mu);
        foobar2(Mu);
    
        return 0;
    }
    Within the function body, you can refer to individual elements of the arrays either through array indexing or through pointer arithmetic:
    Code:
    void foobar1(TypeMu mu[])
    {
        mu[2].CL = 0.0;  /* accessing third element */
        (mu+2)->CL = 0.0;  /* same thing */
    }
    
    void foobar2(TypeMu *mu)
    {
        /*  same thing works here too */
        mu[2].CL = 0.0;  /* accessing third element */
        (mu+2)->CL = 0.0;  /* same thing */
    }
    Obviously, array indexing is easier to write and read than pointer arithmetic.

    BTW, neither notation tells the function how many elements are in the array. You would either have to pass that value as a second parameter or make the last array element a special invalid "end of array" value, like the null-terminator of a character string.
    Last edited by dwise1_aol; July 2nd, 2003 at 01:47 PM.

IMN logo majestic logo threadwatch logo seochat tools logo