Yuval Elmo
Yuval Elmo

Reputation: 35

error C2061 when making structs for linked lists in c

keep getting this error even though i tried to switch places of the structs so they will be declared in the right place.. seems to be the right order this way, but still getting this error. what seems to be the problem ?

typedef struct YListNode {
    int Yval;
    YListNode *next;
}YListNode;

typedef struct YList {
    YListNode *head;
    YListNode *tail;
}YList;

typedef struct XListNode {
    XListNode * prev;
    int Xval;
    YList yList;
    XListNode *next;
}XListNode;

typedef struct List {
    XListNode *head;
    XListNode *tail;
}List;

Upvotes: 2

Views: 81

Answers (2)

ryyker
ryyker

Reputation: 23208

The order of struct definition is not the issue, rather it has to do with using an as yet undefined typedef to define a struct member...

In this declaration:

typedef struct YListNode {
    int Yval;
    YListNode *next;
}YListNode;

The same symbol ( YListNode ) is used for the struct name (or struct tag) and the typedef of the struct. This is a problem for two reasons:

  • The first is ambiguity. Maintaining the code in the future will require extra attention for coders to apply this multiply defined symbol correctly.

  • The second, which addresses your specific question, is that until the struct typedef (YListNode) is defined, it should not be used in the definition of any member of that struct.

This configuration in a CLANG compiler results in this error: 9, 5 error: must use 'struct' tag to refer to type 'YListNode'

To address the issue:
Either choose different symbols for these struct components. For example:

typedef struct yNode {
    int Yval;
    struct yNode *next;
}YListNode;

And apply the same to the other declarations as well.

Or use the following forward declarations placed prior to the struct definition statements:

typedef struct YListNode YListNode;
typedef struct YList YList;
typedef struct XListNode XListNode;
typedef struct List List;

Upvotes: 2

campescassiano
campescassiano

Reputation: 831

You can use the forward declaration to first declare the typedef struct, and then you define them.

Here it is:

    /* forward declaration */
    typedef struct YListNode YListNode;
    typedef struct YList YList;
    typedef struct XListNode XListNode;
    typedef struct List List;

    typedef struct YListNode {
        int Yval;
        YListNode *next;
    }YListNode;

    typedef struct YList {
        YListNode *head;
        YListNode *tail;
    }YList;

    typedef struct XListNode {
        XListNode * prev;
        int Xval;
        YList yList;
        XListNode *next;
    }XListNode;

    typedef struct List {
        XListNode *head;
        XListNode *tail;
    }List;

Upvotes: 1

Related Questions