C - Dereferencing pointer to incomplete type

2019-06-06 08:01发布

问题:

I have read about 5 different questions on the same error, but I still can't find what's the problem with my code.

main.c

int main(int argc, char** argv) {
    //graph_t * g = graph_create(128); //I commented this line out to make sure graph_create was not causing this.
    graph_t * g;
    g->cap; //This line gives that error.
    return 1;
}

.c

struct graph {
    int cap;
    int size;
};

.h

typedef struct graph graph_t;

Thanks!

回答1:

You can't do that since the struct is defined in a different source file. The whole point of the typedef is to hide the data from you. There are probably functions such as graph_cap and graph_size that you can call that will return the data for you.

If this is your code, you should define struct graph inside the header file so all files that that include this header will be able to have the definition of it.



回答2:

When the compiler is compiling main.c it needs to be able to see the definition of struct graph so that it knows there exists a member named cap. You need to move the definition of the structure from the .c file to the .h file.

An alternate method, if you need graph_t to be an opaque data type, is to create accessor functions that take a graph_t pointer and return the field value. For example,

graph.h

int get_cap( graph_t *g );

graph.c

int get_cap( graph_t *g ) { return g->cap; }


回答3:

Must be the order you have things defined. The typedef line needs to show up in the header file that is included by the file that has main().

Otherwise it worked fine for me.



回答4:

lala.c

#include "lala.h"

int main(int argc, char** argv) {
    //graph_t * g = graph_create(128); //I commented this line out to make sure graph_create was not causing this.
    graph_t * g;
    g->cap; //This line gives that error.
    return 1;
}

lala.h

#ifndef LALA_H
#define LALA_H

struct graph {
    int cap;
    int size;
};

typedef struct graph graph_t;

#endif

This compiles without problems with:

gcc -Wall lala.c -o lala