Search code examples
cstructunions

What does "request for member '*******' in something not a structure or union" mean?


Is there an easy explanation for what this error means?

request for member '*******' in something not a structure or union

I've encountered it several times in the time that I've been learning C, but I haven't got a clue as to what it means.


Solution

  • It also happens if you're trying to access an instance when you have a pointer, and vice versa:

    struct foo
    {
      int x, y, z;
    };
    
    struct foo a, *b = &a;
    
    b.x = 12;  /* This will generate the error, should be b->x or (*b).x */
    

    As pointed out in a comment, this can be made excruciating if someone goes and typedefs a pointer, i.e. includes the * in a typedef, like so:

    typedef struct foo* Foo;
    

    Because then you get code that looks like it's dealing with instances, when in fact it's dealing with pointers:

    Foo a_foo = get_a_brand_new_foo();
    a_foo->field = FANTASTIC_VALUE;
    

    Note how the above looks as if it should be written a_foo.field, but that would fail since Foo is a pointer to struct. I strongly recommend against typedef:ed pointers in C. Pointers are important, don't hide your asterisks. Let them shine.