Struct with an array element in C

I recently looked through 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 completely new to C, do I understand correctly that this structure is terribly inefficient in using space due to an array member? What happens when this structure is passed as an argument to a function? Is it completely copied to the stack, including the full array?

Would it be better in most cases to have it double *some_pointerinstead?

+5
source share
6 answers

If you pass on the value yes, it will make a copy of everything. But why do pointers exist.

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

}
+7
source

, , , . , , .

double some_big_array[VERY_LARGE_NUMBER];

double *some_pointer

, / . , .

+2

, ( sizeof (struct foo) , 4 ).

"struct hack" ( ):

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

"struct hack" malloc.

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

, C .

0

. , , . , , , .

0

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

Offtopic: Beware of structural hacking, as it does not strictly comply with the standard ; It ignores auto-complete. However, Unix IPC messaging queues use it (see struct msgbuf), and will almost certainly work with any compiler.

However, functions that use this structure can use pointers to it instead of using a copy.

0
source

All Articles