c - 实现二叉搜索树, "return from incompatible pointer type"

标签 c pointers binary-search-tree

我目前正在学习 C,但在实现二叉搜索树时遇到了问题。

我已经声明了节点和树结构,但是对于以下四个返回或修改每个节点的左右指针的函数,编译器给我“不兼容的指针类型”警告。

我已经尝试阅读其他类似的问题,但我不明白为什么,因为所有类型都应该是 node *

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

typedef struct{
    int data;
    struct node *left, *right;
} node;

typedef struct{
    node *root;
    int size;
} tree;

node* getLeft(node *n){
    return n->left;
}

node* getRight(node *n){
    return n->right;
}

void setLeft(node *n, node *i){
    n->left=i;
}

void setRight(node *n, node *d){
    n->right=d;
}

int main() {
    return 0;
}

错误信息是:

ask.c: In function ‘getLeft’:
ask.c:16:5: warning: return from incompatible pointer type
     return n->left;
     ^
ask.c: In function ‘getRight’:
ask.c:20:5: warning: return from incompatible pointer type
     return n->right;
     ^
ask.c: In function ‘setLeft’:
ask.c:24:12: warning: assignment from incompatible pointer type
     n->left=i;
            ^
ask.c: In function ‘setRight’:
ask.c:28:13: warning: assignment from incompatible pointer type
     n->right=d;
             ^

最佳答案

节点 typedef 声明不正确。它引用了不存在的struct node。解决方法是简单地使用命名结构而不是匿名结构(可能是您打算做的)。

typedef struct node {
    int data;
    struct node *left, *right;
} node;

关于c - 实现二叉搜索树, "return from incompatible pointer type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37647698/

相关文章:

c++ - 为什么 CUDA 固定内存这么快?

c - 启动存储 pid 守护进程的简单脚本

c - 用指针在 C 中包装字符串

有人可以帮我解释一下这个递归函数吗?

c - 这段代码有什么Bug?

java - 二叉搜索树的搜索和比较内容的大O

C中的cc编译器问题

c++ - 在 C++ 中通过指针传递比通过引用传递有好处吗?

c++ - BST - 节点神秘地被分配到错误的一侧

c - 如何初始化指针指向的结构的成员?