错误:取消引用指向不完整类型的指针 [英] ERROR: dereferencing pointer to incomplete type
问题描述
//下面的代码行给出了上面提到的错误
// printf(%d,root-> left-> info);
//算法或编码是否有任何缺陷
//The following line of code gives above mentioned error
//printf("%d",root->left->info);
// is there any flaw in the algorithm or coding
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct Node
{
int info;
struct node* left;
struct node* right;
}node;
void insert(node *root,int item)
{
node *parent,*cur;
parent=NULL;
cur=root;
while(cur!=NULL)
{
parent=cur;
if(item<=cur->info)
cur=cur->left;
else
cur=cur->right;
}
if(parent==NULL)
{
root->info=item;
root->left=NULL;
root->right=NULL;
}
else if(item<parent->info)
{
node *newNode=(int*)malloc(sizeof(node));
newNode->info=item;
newNode->left=NULL;
newNode->right=NULL;
parent->left=newNode;
}
else
{
node *newNode=(int*)malloc(sizeof(node));
newNode->info=item;
newNode->left=NULL;
newNode->right=NULL;
parent->right=newNode;
}
}
int main()
{
node *root=(node*)malloc(sizeof(node));
root->info=6;
root->left=NULL;
root->right=NULL;
insert(root,4);
printf("%d",root->left->info);
getch();
}
推荐答案
问题在于节点结构的定义:
The problem lies in the definition of your node structure:
typedef struct Node
{
int info;
struct node* left; // <----
struct node* right; // <----
}node;
没有struct node,只有struct Node(大写)。因此左
指向尚未定义的结构的指针,编译器很乐意接受,直到您尝试取消引用它。所以将左边定义为struct Node *,一切都会好的。
顺便说一句。你不能将 left
定义为node *,因为此时尚未定义node。
There is no "struct node", but only a "struct Node" (uppercase). And hence is left
a pointer to a yet undefined structure, which the compiler gladly accepts until you try to dereference it. So define left as "struct Node*" and everything will be fine.
Btw. you cannot define left
as "node*" because the "node" has not yet been defined at that point.
这篇关于错误:取消引用指向不完整类型的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!