accessing struct: derefrencing pointer to incomplete type

后端 未结 3 951
盖世英雄少女心
盖世英雄少女心 2021-01-27 08:58

When I\'m trying to use and access the pointers to my structs i keep getting the annoying message of \"dereferencing pointer to incomplete type\" ....

For e

相关标签:
3条回答
  • 2021-01-27 09:25

    If you want to hide the definition of a structure (by sticking the actual struct { block in a single C file and only exposing a typedefed name in the header, you cannot expect to access the fields directly.

    One way around this is to continue with the encapsulation, and define accessor functions, i.e. you'd have (in user.h):

    const char * user_get_name(const User user);
    void         user_set_name(User user, const char *new_name);
    ...
    

    Please note that including the * in the typedef is often confusing, in my opinion.

    0 讨论(0)
  • 2021-01-27 09:31

    The problem is that the C file doesn't have access to the implementation of that strucure.

    Try to move the definition of the structure in the header file.

    0 讨论(0)
  • 2021-01-27 09:39

    As I understand it you try to access the members of User...

    ...via a Element, which is a void *. This can not work, because the compiler does not know what type it should dereference. For example:

    int *intPtr = getIntPtr();
    //Here the compiler knows that intPtr points to an int, so you can do
    int i = *intPtr;
    
    User *userPtr = getUserPtr();
    //Here the compiler knows that userPtr points to an instance of User so you can do 
    User usr = *usrPtr;
    //or access its member via ->
    auto x = usr->someMember;
    
    Element el = getElementFromSomewhere();
    //el is of type void *!! void *can point to anything and everything
    //the compiler has no clue what you want to do! So this both fails:
    usr = *el; 
    el->someMember;
    

    You first need to tell the compiler what your void * is pointing to. To do that you cast the pointer:

    Element el = getElementFromSomewhere();
    User *usrPtr = (User *)el;
    

    I hope I understood your problem and this helps :)

    0 讨论(0)
提交回复
热议问题