Search code examples
cpointersdereference

c - dereferencing pointer to incomplete type - error with a pointer to a char*


I have a problem accessing a char* that is in another struct, heres the code:

User_Network.c:

struct User_Networks_t {
    SocialNetwork network;
};

typedef struct User_Networks_t* User_Networks;


void aaa(User_Networks u1)
{
    u1->network->Name = "test";  /// ERROR: dereferencing pointer to incomplete type 
}

Here is what I have in the SocialNetwork.h:

typedef struct SocialNetwork_t* SocialNetwork;

the struct that is in the SocialNetwork.c:

struct SocialNetwork_t {
    char *Name;
};

Why am I getting that error?


Solution

  • When you define your struct SocialNetwork_t in the implementation file SocialNetwork.c, the compiler can not know about the contents of the struct when it is compiling User_Network.c, if you only use #include <SocialNetwork.h there. The compiler parses the header file SocialNetwork.h and knows that it should find the definition of the struct SocialNetwork_t later on, but doesn't encounter that definition when compiling the dereference in void aaa(...). So, put the complete struct definition into SocialNetwork.h.

    [update] I'll elaborate a little bit more on that answer. I guess your file User_Network.c looks like this:

    #include "SocialNetwork.h"
    struct User_Networks_t {
        SocialNetwork network;
    };
    
    typedef struct User_Networks_t* User_Networks;
    
    
    void aaa(User_Networks u1)
    {
        u1->network->Name = "test";  /// ERROR: dereferencing pointer to incomplete type 
    }
    

    When your compiler compiles this, the preprocessor substitutes `#include "SocialNetwork.h" with the content of that file, which gives you:

    /* START content from the included file */
    typedef struct SocialNetwork_t* SocialNetwork;
    /* END */
    struct User_Networks_t {
        SocialNetwork network;
    };
    
    typedef struct User_Networks_t* User_Networks;
    
    
    void aaa(User_Networks u1)
    {
        u1->network->Name = "test";  /// The struct SocialNetwork is not defined here
    }
    

    This will be the complete file when the compiler starts the actual compilation. So, when you try to access the Name field from struct SocialNetwork, the compiler didn't see the struct but only the typedef of a pointer type. Hence it can not know to which type you are actually referring.