Question

I have this in a C file:

struct T
{
    int foo;
};

the C file has an include to an h file with those lines:

typedef struct T T;
void listInsertFirst(T data, int key, LinkedList* ListToInsertTo);

the function listInsertFirst is the one I'm getting the warning on. How can I fix it?

Was it helpful?

Solution

As we've found out in the comments, the problem was that the definition of struct T occurred after the definition of T in the header. You really have things backwards here. The header should be defining all the types and function prototypes and your C files should be using them.

What you want to be doing instead is change the signature of your insert function to receive a pointer to your data and the size of the data. Then you can allocate some memory for the data, copy it and store it. You don't need a specific type, just declare it a void *.

void listInsertFirst(void *data, size_t data_size, int key, LinkedList* ListToInsertTo);

Then the caller would do something like this:

struct T { int foo; };
struct T x = { ... };
int someKey = ...;
LinkedList *someList = ...;
listInsertFirst(&x, sizeof x, someKey, someList);

OTHER TIPS

When you include the header file, the compiler knows that T is a structure of unknown size and that listInsertFirst wants one as its first argument. But the compiler cannot arrange a call to listInsertFirst as it doesn't know how many bytes to push on the stack for the T data parameter, the size of T is only known inside the file where listInsertFirst is defined.

The best solution would be to change listInsertFirst to take a T* as its first argument so your header file would say this:

extern void listInsertFirst(T *data, int key, LinkedList* ListToInsertTo);

Then you get an opaque pointer for your T data type and, since all pointers are the same size (in the modern world at least), the compiler will know how to build the stack when calling listInsertFirst.

Are you sure it is the first parameter that is the problem? To be sure, try changing the parameter type from T to int temporarily. More than likely, the third parameter is actually the problem.

Many compilers don't point at the problem in these sorts of issues very well.

Try to move the structure definition to the h file, before the typedef.

  1. Define struct T in header, not in .c file;
  2. Choose different names for structure and typedef.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top