4

I am trying out some basic datastructure stuff in C. And I am coming back to C after a long time. Here is my simple struct:

typedef struct
{
    int data;
    LLNode *next; //Error: unknown type name 'LLNode'
}LLNode;

But it gives a compilation error as shown above. Is it because while compiling struct compiler is not aware of existence of LLNode? That means I must be first declaring LLNode before struct. Is it like that? If yes how I am supposed to do it?

4 Answers 4

13

Do this that way:

typedef struct LLNode LLNode;

struct LLNode {
    int data;
    LLNode *next; //No error
};

You cannot use LLNode type before it is defined. With this method you declare what is LLNode first. Even though struct LLNode is not defined yet, this declaration suffice to declare LLNode * members (but you could not declare a LLNode member yet) as a pointer's size does not depend on the pointer's type.

Sign up to request clarification or add additional context in comments.

1 Comment

You might wanna add an explanation for why that works, for completeness sake.
6

The data member next of the structure is declared the type LLNode, which is unknown.

The corrected example

typedef struct LLNode
{
    int data;
    struct LLNode *next; //Error: unknown type name 'LLNode'
}LLNode;

Take into account that the structure tag name and the typedef name are in different name spaces. So you may use these two names simultaneously like struct LLNode and just LLNode.

Comments

2

The typedef is incomplete until the end, so LLNode is not available as a type name inside the struct. However, struct tag would be available, so you could do this:

typedef struct LLNode
{
    int data;
    struct LLNode *next;
} LLNode;

This produces a struct with an identical structure to what is in your post, because struct LLNode is typedef-ed to LLNode.

2 Comments

how this compares to defining typedef before struct as explained by @jdarthenay in answer below?
@Mahesha999 It's a matter of preference. Your struct definition is independent of typedef, you could combine them or separate them out as you wish; it does not matter to the compiler, as long as it sees both of them. Yet another possibility is to define struct without typedef first, and then add typedef struct LLNode LLNode at the end. The effect is going to be the same in all three cases.
1

you can use:

typedef struct LLNode LLNode;
struct LLNode
{
int data;  
LLNode *next;   
};   

1 Comment

Hey you should use the embedded code inputter like what you see above in other answers, instead of displaying it like you have above. Click the "{}" button to put code in like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.