Struct with array member in C

19,013

Solution 1

If you pass by value yes it will make a copy of everything. But that's why pointers exist.

//Just the address is passed 
void doSomething(struct foo *myFoo)
{

}

Solution 2

Being passed as an argument it will be copied which is very inefficient way of passing structures, especially big ones. However, basically, structs are passed to functions by pointer.

Choosing between

double some_big_array[VERY_LARGE_NUMBER];

and

double *some_pointer

depends only on the program design and how this field/structure will be used. The latter allows using variable size storage, however may need dynamic allocation.

Solution 3

There are plenty of reasons to use arrays in structs. Among them is the fact that structs are passed to functions by value, while arrays are passed by reference. That said, this struct is probably passed to functions with pointers.

Solution 4

As others have said, objects of that type are usually passed around with pointers (always sizeof (struct foo) bytes, often 4 bytes).

You may also see the "struct hack" (also passed around with pointers):

struct foo {
    int some_innocent_variables;
    double some_array[]; /* C99 flexible array member */
    /* double some_array[1]; ** the real C89 "struck hack" */
}

This "struct hack" gets an array sized by the malloc call.

/* allocate an object of struct foo type with an array with 42 elements */
struct foo *myfoo = malloc(sizeof *myfoo + 42 * sizeof *myfoo->some_array);
/* some memory may be wasted when using C89 and
   the "struct hack" and this allocation method */
Share:
19,013
lindelof
Author by

lindelof

David's dayjob consists of working as a consultant for an IT company in Geneva. After dark he works on his main interests, which include home and building automation.

Updated on June 25, 2022

Comments

  • lindelof
    lindelof almost 2 years

    Recently I reviewed some C code and found something equivalent to the following:

    struct foo {
        int some_innocent_variables;
        double some_big_array[VERY_LARGE_NUMBER];
    }
    

    Being almost, but not quite, almost entirely a newbie in C, am I right in thinking that this struct is awfully inefficient in its use of space because of the array member? What happens when this struct gets passed as an argument to a function? Is it copied in its entirety on the stack, including the full array?

    Would it be better in most cases to have a double *some_pointer instead?

  • altendky
    altendky over 10 years
    To stay as close to passing-by-value as possible while still gaining the pass-by-reference efficiency you can use struct foo const * const myFoo. This will tell the compiler to warn you when you accidentally try to modifier either the pointer or pointed-to value.