简体   繁体   中英

Struct with array member in C

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?

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

}

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.

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 */

是的,在C中,由于效率原因,您通常会将指针传递给周围的结构。

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM