节点正在提供垃圾值
我正在做二叉树的C程序,同时在2或3个节点之后将节点插入到树中,子节点具有垃圾值并崩溃我正在xcode中做任何想法...
Bnode createTreeNode()
{
Bnode node=(Bnode)malloc(sizeof(Bnode));
return node;
}
Bnode addTreeNode(Bnode inNode, char *inData)
{
int compareValue;
if (inNode == NULL)
{
inNode = createTreeNode();
inNode->leftNode=NULL;
inNode->rightNode=NULL;
stpcpy(inNode->data,inData);
}
else if((compareValue=strcmp(inData,inNode->data))==0)
{
inNode->count=inNode->count+1;
}
else if(compareValue>1)
{
inNode->rightNode=addTreeNode(inNode->rightNode,inData);
}
else
{
inNode->leftNode = addTreeNode(inNode->leftNode,inData);
}
return inNode;
}
这就是我创建节点并将其插入到树中的方式。
i am doing c program of binary tree while inserting the node to tree after 2 or 3 nodes the child node having garbage value and crashing i am doing in xcode any idea...
Bnode createTreeNode()
{
Bnode node=(Bnode)malloc(sizeof(Bnode));
return node;
}
Bnode addTreeNode(Bnode inNode, char *inData)
{
int compareValue;
if (inNode == NULL)
{
inNode = createTreeNode();
inNode->leftNode=NULL;
inNode->rightNode=NULL;
stpcpy(inNode->data,inData);
}
else if((compareValue=strcmp(inData,inNode->data))==0)
{
inNode->count=inNode->count+1;
}
else if(compareValue>1)
{
inNode->rightNode=addTreeNode(inNode->rightNode,inData);
}
else
{
inNode->leftNode = addTreeNode(inNode->leftNode,inData);
}
return inNode;
}
this is how i creating node and inserting it to tree.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您提供了指向结构体的指针的大小作为参数,而不是结构体的大小 本身。
因此,分配给 Bnode 的内存较少,最终您必然会得到垃圾值和分段错误。
将其更改为类似
PS: [1] C 中不需要显式转换 (Bnode) 的内容。
You have provided size of the pointer to the struct as the argument instead of size of the struct itself.
As a result, less memory is allocated to
Bnode
and eventually you are bound to get garbage values and segmentation faults.Change it to something like
P.S.: [1] Explicit casts (Bnode) not required in C.
您为节点声明了一个指针,但实际上没有为其分配任何存储空间,因此您有一个 悬空指针。您需要为每个新节点调用
malloc()
(或calloc()
),以分配存储空间。You declared a pointer for your node, but you didn't actually allocate any storage for it, so you have a dangling pointer. You need to call
malloc()
(orcalloc()
) for each new node, in order to allocate storage.