C语言:使用结构实现二叉搜索树时出错

时间:2017-07-22 16:55:50

标签: c file struct binary-search-tree function-pointers

/* These are struct definitions I am using */
struct PdsNdxInfo{
    int key;
    int offset;
};

struct PdsInfo{
    FILE *repo_fptr;
    FILE *ndx_fptr;
    char repo_name[MAX_NAME_LEN];
    int repo_status;  
    int num_recs;
    struct PdsNdxInfo ndxEntries[MAX_RECS];
};


/*This is the code */

//BST Creation
struct PdsNdxInfo temp[pdsInfo.num_recs];
fseek(pdsInfo.ndx_fptr,0,SEEK_SET);
fread(temp, sizeof(struct  PdsNdxInfo), pdsInfo.num_recs, pdsInfo.ndx_fptr);


int i=0;
while(i < pdsInfo.num_recs){
    printf("********%d  %d",temp[i].key,temp[i].offset);
    if(root==NULL) {
        root =insert(root,temp[i].key,temp[i].offset); //getting error
    }
    else {
        insert(root,temp[i].key,temp[i].offset);
    }
    i++;    
}

/* This is the function definition */
struct node *newNode(int k,int o){
    struct node *temp =  (struct node *)malloc(sizeof(struct node));
    temp->key = k;temp->offset = o;
    temp->left = temp->right = NULL;
    return temp;
}

struct node* insert(struct node* root, int k,int o) {
    if (root == NULL) return newNode(k,o);
    if (k < root->key)
    root->left  = insert(root->left, k,o);
    else if (k > root->key)
    root->right = insert(root->right, k,o);   

    return root;
}

编译错误:

pds_version2.c: In function ‘pds_store’:
pds_version2.c:119:9: warning: assignment makes pointer from integer 
without a cast [enabled by default]
root = insert(root,pdsInfo.ndxEntries[pdsInfo.num_recs-
1].key,pdsInfo.ndxEntries[pdsInfo.num_recs-1].offset);
     ^
pds_version2.c: At top level:
pds_version2.c:180:14: error: conflicting types for ‘insert’
struct node* insert(struct node* root, int k,int o)
          ^
pds_version2.c:66:10: note: previous implicit declaration of ‘insert’ 
was here
root =insert(root,temp[i].key,temp[i].offset);

无法弄清楚错误发生的原因基本上我正在尝试创建二进制搜索树以及上面的两个方法是insert和newnode但是会出现编译时错误。

新节点是一个左右两个指针和两个数据值的结构。但我无法弄清楚为什么会出现这样的错误“赋值使得整数指针没有强制转换[默认情况下启用]”

1 个答案:

答案 0 :(得分:1)

您应该将insert函数放在使用它之前。 或者简单地将函数声明放在:

之前
struct node* insert(struct node* root, int k,int o);

void code()
{
  //use insert function here
}
struct node* insert(struct node* root, int k,int o)
{
  //insert function definition
}