C - Dereferencing pointer to incomplete type

12,895

Solution 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.

Solution 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; }
Share:
12,895
user1255321
Author by

user1255321

Updated on June 04, 2022

Comments

  • user1255321
    user1255321 almost 2 years

    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!