简体   繁体   中英

typedef struct in header and dereference pointer to incomplete type

I'm quite rusty in C, but I think I'm having issues understanding the proper usage of using typedef s in headers, defining the actual struct's structure in the implementation file, and then using the struct in a third file.

I wrote a queue data-structure that has a type defined as such:

typedef struct queue
{
    int count;
    qnode_t *head;
    qnode_t *tail;
} queue_t;

Where qnode_t is a struct that's only used within the queue's implementation file.

Within my header I have this:

typedef struct queue queue_t;

When using this queue_t type within another file I'm attempting to get the queue's length like this:

queue_t *work_queue;
...
int length = work_queue->count;

However, on that line where I'm looking up count I get the compiler error:

dereferencing pointer to incomplete type

I've been doing a lot of research about how to properly define types in C, but I think I just keep confusing myself more and more instead of getting clarity since many examples are either conflicting with other resources or are too simplified for me to put to practical use.

Would I be getting this error because the 'count' variable within the struct isn't defined there? If this is the case, then can I define the struct in BOTH the implementation and header? If so, can the header only have the count variable defined since the head & tail should be hidden/private? (I miss OOP) Should I just be making another function that takes a queue_t* and returns its length as size_t ?

you can only dereference defined types, not declared types. Type declarations are useful to type-check opaque pointers, but object fields are not visible, cannot be accessed. You need to move the typedef into the header to access fields of your queue object.

Edit: from the questions/answers below:

Yes, two identical struct definitions are seen as the same typedef. You could omit fields if you never had both definitions in the same source file, but don't do it, that leads to bugs and maintenance confusion. Better to use a naming convention eg names starting with underscores are internal.

The convention is to define the struct in the header then include the same header in the implementation file. This keeps the published layout in sync with the implementation

It is not possible in C to dereference any pointer unless the compiler has access to complete information about the type of what is pointed at. For struct pointers, that means a complete struct definition is needed.

So, when compiling the code that is complaining about an incomplete type, the compiler needs to have visibility of the complete definition of the struct type, not just the typedef of the pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM