Question

Hello I am relatively new to C programming. Here is my problem:

I am trying to use a predefined generic queue structure from a header file that is included in my test.c one. However, when I try to use that structure and the functions defined in the header, I get errors associated with 'incomplete type' and I cannot figure out what exactly the compiler does not 'see'.

Here is my header:

#ifndef __GENERIC_QUEUE
#define __GENERIC_QUEUE

typedef struct gqueue GQueue;
typedef void *GQueueElement;

GQueue *create_gqueue (void); 
int destroy_gqueue(GQueue *gq);

Here is the .c file:

#include <stdio.h>
#include <stdlib.h>
#include "generic_queue.h"
#include "TCB.h"

void main(){
    GQueue *qp;
    qp = malloc(sizeof(GQueue));
    qp = *create_gqueue();
    printf("created");

}

Here is what I get when compiling:

$ gcc test1.c
test1.c: In function ‘main’:
test1.c:8:24: error: invalid application of ‘sizeof’ to incomplete type ‘GQueue’
  qp = malloc(sizeof(GQueue));
                    ^
test1.c:9:7: error: dereferencing pointer to incomplete type
  qp = *create_gqueue();
Was it helpful?

Solution

What appears to be the problem is that though

typedef struct gqueue GQueue;

defines GQueue to be used instead of struct gqueue, that struct is itself not defined. Perhaps you need

#include "gqueue.h"

If the definition of the struct is not included, then you can not use sizeof(GQueue) because the size is not known to the compiler. However, the program can still compile and run with GQueue being opaque, so long as you use only the exported interface. It does appear you don't need to even create a GQueue with malloc; you can simply call create_gqueue.

qp = malloc(sizeof(GQueue));   // <---- not necessary
qp = create_gqueue();         // <---- all you need
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top