我目前正在学习 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/