I wrote the following code:
struct DVDARRAY
{
int length;
pDVD* dvds;
};
typedef struct DVDARRAY DVDARRAY_t;
//...
int main()
{
int i;
char c;
DVDARRAY_t* dvds;
poDAOproperties props;
props = get_dao_properties();
dvds = (DVDARRAY_t*) DVDDAO_read_raw_filter(props, "id = 1");
printf("title->: %s", dvds->dvds[0]->title);
}
and in another file the following is defined:
DVDARRAY_t* DVDDAO_read_raw_filter(poDAOproperties properties, char* filter)
{
DVDARRAY_t *dvds;
// ...some code...
dvds = malloc(sizeof(DVDARRAY_t));
// ...some code...
return dvds;
}
Now my question: when I try to compile these files I get the following warning:
src/main.c: In Funktion »main«:
src/main.c:80:9: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
Line 80 of main.c is exactly that line:
dvds = (DVDARRAY_t*) DVDDAO_read_raw_filter(props, "id = 1");
What can I do?
You do not list the file names above so I will just call them main.c
and dvd.c
.
In main.c
, you make a call to the otherwise undeclared function DVDDAO_read_raw_filter
. This tells the compiler to assume that the function exists, has an unknown (but fixed) set of arguments, and has a return value of type int
.
In dvd.c
you define the function DVDDAO_read_raw_filter
with fixed (and known) arguments, returning type DVDARRAY_t*
. (Presumably you have to repeat the definition of DVDARRAY_t
first.)
Note that main.c
believes something untrue about DVDDAO_read_raw_filter
, namely, that it has return type int
. This is causing your compile-time diagnostic. By luck (you can decide for yourself whether this is good or bad luck :-) ) the program runs successfully in spite of this incorrect belief.
To fix the problem, tell main.c
about the function before calling it, i.e., declare it. You can also get a more explicit warning from gcc by adding -Wimplicit-function-declaration
to your compile-time flags.
In general, it's a good idea to put struct
definitions, typedef
s, and function declarations into a header file (e.g., dvd.h
) and then #include
that header in the various C source files that make use of the definitions and declarations. That way the compiler can compare the function declarations against the function definitions, and you need not repeat the contents of struct
s and the names of typedef
s in multiple .c
files.