1
votes

Error: Dereferencing pointer to incomplete type

Codeblocks gives me this error in main.c line 10 (print_bst(tree->root)) (dereferencing pointer to incomplete type) while i'm creating a Binary Search Tree and I can't find the cause to this error.

BST.h

typedef struct Node Node;
typedef struct Tree Tree;
Tree *create_bst();
Node *create_node(int data);
void insert_bst(Tree *tree);
void print_bst(Node *root);

BST.c

#include <stdio.h>
#include <stdlib.h>

typedef struct Node{
    void *dataPtr;
    int data;
    struct Node *left;
    struct Node *right;
} Node;

typedef struct Tree{
    int count;
    Node* root;
} Tree;

Tree *create_bst()
{
    Tree *tree = (Tree*) calloc(1,sizeof(Tree));
    if(tree == NULL){
        printf("calloc() failed!\n");
        return NULL;
    }

    tree->count = 0;
    tree->root = NULL;

    return tree;
}

Node *create_node(int data)
 {
    Node *node = (Node*) calloc(1, sizeof(Node));
    if(node == NULL){
        printf("calloc() failed!\n");
        return NULL;
    }

    node->data = data;
    node->right = NULL;
    node->left = NULL;

    return node;
 }

main.c

#include <stdio.h>
#include <stdlib.h>
#include "BST.h"

int main()
{
    Tree *tree = create_bst();
    while(1){
        insert_bst(tree);
        print_bst(tree->root);
    }

    return 0;
}

The error message refers to line 10 in main.c, (print_bst(tree->root)).

2

2 Answers

6
votes
    print_bst(tree->root);

yeah, that's not going to work, main.c does not #include anything that can tell it that tree has a root element.

The simplest way to fix this is move the definition of Tree into BST.h where main.c can access it.

2
votes

Your header file that is included in main

#include "BST.h"

does not contain definitions of structures Node and Tree. It only declares them

typedef struct Node Node;
typedef struct Tree Tree;

Thus in thsi statement

   print_bst(tree->root);

the compiler will issue an error because it does not know whether structure Tree has data member root.

Also it seems that data member void *dataPtr might be removed from structure Node because it is not used. For temporary objects you could declare local variables in the functions.