I have declared a typedef struct on header files as follows:
myheader.h
typedef struct mystruct mystruct;
myheader.c
typedef struct mystruct{
double *ptr1;
double *ptr2;
int *ptr3;
mystruct *ptr4;
mystruct *ptr5;
}mystruct;
program.c
#include "myheader.h"
int main()
{
mystruct *A = (mystruct *)malloc(sizeof(mystruct));
}
when i try to compile using:
gcc -o myprogram myprogram.c myheader.c
i get the following error:
error: invalid application of ‘sizeof’ to incomplete type ‘mystruct’ {aka ‘struct mystruct’}
mystruct * A = (mystruct *)malloc(sizeof(mystruct));
Is there something wrong with my code or am I compiling in the wrong way?
As @someprogrammerdude has already pointed out in his comment about translation units: when the compiler compiles main.c it has only knowledge about main.c and the included headers. So all it knows is that that there is a struct typedef
ed as mystruct
but it knows nothing about its content and thus cannot determine ts size either, so you cannot use sizeof()
. For the same reason you couldn't access any struct members, int *p = mystruct->ptr3
; or mystruct->ptr1 = &mydouble;
wouldn't compile as well.
Nevertheless that design is quite common. Let's assume you want to encapsulate every access to mystruct
in an OO like manner. Then you have a source, say mystruct.c where you actually define the structure (like you did in myheader.c) and provide all neccessary getter and setter functions (including an allocation function). Then in every other source you could pass struct pointers any way you like but for everything else you have to use the designated functions.
The advantage of that approach is that in the future you're free to modify the struct whithout having to recompile every source that uses it.