Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Struct with array member in C

Tags:

arrays

c

struct

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?

like image 812
lindelof Avatar asked Sep 13 '10 20:09

lindelof


2 Answers

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

}
like image 155
Brian R. Bondy Avatar answered Oct 23 '22 07:10

Brian R. Bondy


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.

like image 30
pmod Avatar answered Oct 23 '22 05:10

pmod