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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With