Search code examples
cpointersstructgcc-warning

Can't assign address of struct to a variable whose type is a typedef of pointer to that struct


I'm somewhat new to C, I'm learning it at uni, and I think I might be misunderstanding something about typedefs. Here's my code:

struct stackNode
{
    char data;
    struct stackNode *nextPtr;
};
typedef struct stackNode StackNode;
typedef struct StackNode *StackNodePtr;

int main()
{
    StackNode stack;
    StackNodePtr stackPtr = &stack;
}

This gives me this warning:

warning: initialization from incompatible pointer type [enabled by default]
     StackNodePtr stackPtr = &stack;
                             ^

However if I replace that line with this:

StackNode *stackPtr = &stack;

It works fine.

Unfortunately I'm not seeing the real difference here. Isn't typedef struct StackNode *StackNodePtr; just a sort of "wrapper type" for a pointer to the Stack struct? I've got a pretty good grasp of pointers and structs, but I don't know what's going on here. I'm sure I'm just missing something small.

By the way, I'm compiling in c89 mode using gcc.


Solution

  • Problem is this type definition:

    typedef struct StackNode *StackNodePtr;
    

    There is no struct StackNode. Only struct stackNode and StackNode exist. So you'll need to use either one of those in the typedef.

    But better solution is to not hide pointers behind typedef at all:

    1. It makes the pointer more clearly visible.
    2. It works better with type qualifiers, such as const and volatile. If you define StackNodePtr, you may have to define ConstStackNodePtr, VolatileStackNodePtr and ConstVolatileStackNodePtr also.

    So, get rid of StackNodePtr and simply use the method you already tried:

    StackNode *stackPtr = &stack;  // stackPtr is clearly a pointer