TLD
TLD

Reputation: 8135

compiler error - dereferencing pointer to incomplete type In C programming

Can you explain this error for me?

In my A.h file:

struct TreeNode;
struct TreeHead;
typedef struct TreeNode * Node;
typedef struct TreeHead * Head;

In my A.c file:

struct TreeNode {
    char* theData;
    Node Left;
    Node Right;
} ;

struct TreeHead{
    int counter;
    char type;
    Node Root;
};

Head Initialisation() {
    Head treeHead;
    treeHead = malloc(sizeof (struct TreeHead));
    treeHead->Root = malloc(sizeof (struct TreeNode));
    return treeHead;
}

In my Main.c file:

Head head;
Node tree;
int choose =5;
head = Initialisation(); 
(head->Root) = tree; //When compiling, this line has an error: error: dereferencing pointer to incomplete type

haed->Root will return a Node pointer, tree is also a Node pointer. So why error is dereferencing pointer to "incomplete" type?

Upvotes: 2

Views: 3009

Answers (3)

VGE
VGE

Reputation: 4191

The TreeHead struct is defined in A.c and is not visible in Main.c

You have to put it in a header file to access it.

Upvotes: 2

Jens Mühlenhoff
Jens Mühlenhoff

Reputation: 14873

You have to put the structs into the header file as well.

The compiler does not know the exact memory layout of the structs in the main.c file, because they are not declared in the header.

Upvotes: 0

The Archetypal Paul
The Archetypal Paul

Reputation: 41749

Because in compiling main.c, only the typdef is visible, not the definition of struct Treenode (which is in A.c). So the compiler does not know what is in the struct, and so does not know it even contains a Root node

Upvotes: 3

Related Questions