Is it possible to make an array of declared but not defined types? This is what I would like to do:
typedef struct _indiv indiv;
typedef indiv pop[];
and let somebody else decide what an individual’s members actually are by defining the struct _indiv in another .c or .h file (and then linking everything together).
(For the semantics, indiv is an individual and pop is a population of individuals.)
But the compiler complains:
error: array type has incomplete element type
I could replace the second typedef by
typedef indiv * pop;
And use pop like an array by accessing the elements like p[i] (with p of type pop), but if I do that the compiler will complain that
error: invalid use of undefined type ‘struct _indiv’
error: dereferencing pointer to incomplete type
I suppose since typedef struct _indiv indiv is only a declaration, the compiler does not know at compile time (before the linkage) how much space the struct requires and that it doesn’t like it, thus forbiding to do what I’m trying. But I would like to know why and if there is a possible way to acheive what I want.
Thanks
You are right that the compiler doesn’t know the size of incomplete types (in your example,
struct _indivis an incomplete type), which is why you cannot declare a variable of such a type. This includes creating an array of such types.However, this doesn’t really matter, because if you don’t have the complete definition of the type, then you can’t sensibly access its members anyway: if you write
p[i].foo, how do you know if the type actually has a member calledfoo, and if it does, what type it is?If you want the
structtype’s members to be defined in another.cfile (this is known as an “opaque type”), then you must only ever create and handle pointers to the struct. Your other.cshould contain all the code that actually accesses thestructitself. The file that has only the incomplete type would contain code like:…and the source file with the complete definition of the
structwould contain the implementation ofnew_individual(),print_individual()and so on.Under this scheme, the easiest way to deal with a population is to make it an array of pointers to
indivstructs.