tags:

views:

163

answers:

6

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?

A: 

Yes, in C you would usually pass a pointer to the structure around due to efficiency reasons.

Jim Brissom
+6  A: 

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)
{

}
Brian R. Bondy
A: 

Being passed as an argument it will be copied which is very ineffective 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.

Pmod
+1 due to unmotivated downvote
Bart van Ingen Schenau
A: 

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.

Nathon
A: 

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 */
pmg
A: 

EDIT: That structure is fine as long as you pass it by reference (using a pointer).

Offtopic: Beware of the struct hack, as it is not strictly standard compliant; it ignores the automatic padding. The Unix IPC messaging queues use it (see struct msgbuf), though, and it is almost certainly to work with any compiler.

That said, the functions that use that structure may use pointers to it instead of using a copy.

Pablo Alejandro Costesich