Reputation: 125
I have a header file which gives the definition
typedef struct dyn_array dyn_array_t
I have a .c file which implements it
struct dyn_array {
size_t size;
void* array;
};
In a different .c file I pass a pointer of this type to a function.
bool first_come_first_serve(dyn_array_t* ready_queue){
size_t limit = ready_queue->size;
//...
}
I can't figure out what I'm doing wrong here.
Upvotes: 1
Views: 170
Reputation: 12718
The compiler needs to complete the type definition to be able to dereference a pointer to it and access its fields. You have to put the type definition in a header (possibly different than the one you used to put the typedef
declaration) and include it in the second file also, to be able to access past the pointer. The compiler allows you to access a pointer to incomplete type definition, as long as you don't need the details of that type. As in your second file, the compiler knows nothing about how the structure is built, so it cannot access the size
field.
If you need some parts of your code not to be able to access the internal details of your data type, and others be completely aware of it, then prepare two header files (one public and other private) like this:
typedef struct dyn_array dyn_array_t;
size_t get_size(const dyn_array_t* ready_queue);
#include "dynarry.h"
struct dyn_array {
size_t size;
void *array;
};
and then, in the modules using as clients the library include only the "dynarry.h"
, while in the internal implementation you #include "dynarryP.h"
. This is somewhat similar to object oriented programming, in relation to hidding internal implementation details.
Upvotes: 1
Reputation: 154601
The other .c file does not see the struct dyn_array
definition. It has no understanding of the members like size
.
If more than 1 .c file needs to understand the structure, move the below to the .h file
struct dyn_array {
size_t size;
void* array;
};
The alternative is to create a function that gets the member and keep the definition of dyn_array_t
local in dyn_array.c
. This is information hiding - a good design goal.
// in dyn_array.h
typedef struct dyn_array dyn_array_t;
size_t get_size(const dyn_array_t* ready_queue);
// in different.c
#include <dyn_array.h>
bool first_come_first_serve(dyn_array_t* ready_queue){
size_t limit = get_size(ready_queue);
//...
}
// in dyn_array.c
#include <dyn_array.h>
struct dyn_array {
size_t size;
void* array;
};
size_t get_size(const dyn_array_t* ready_queue) {
return ready_queue->size;
}
Upvotes: 2
Reputation: 9872
"Incomplete Type" means you have only declared / used the type, and not explained it. Your second .c
file might #include "a.h"
but note that the definition of dyn_array
is in a.c
and not a.h
To fix this, both declare and define dyn_array
in a.h
:
struct dyn_array {
size_t size;
void* array;
};
Upvotes: 1