gpt4 book ai didi

c - 结构体递归内存处理问题

转载 作者:行者123 更新时间:2023-11-30 15:47:39 25 4
gpt4 key购买 nike

我已经为我的程序构建了一个二叉搜索树。这是我的代码:

struct node {
int steps;
int x;
int y;
struct node *left;
struct node *right;
}*head;

typedef struct node *Node;

Node createStepsBinaryTree(Node head, int newStepsInt, int x, int y){
if (head == NULL) {
head = (Node)malloc(sizeof(Node));
if (head==NULL) {
return NULL;
}else{
head->steps = newStepsInt;
head->x = x;
head->y = y;
head->left = head->right = NULL;
}
}else{
if (head->steps > newStepsInt) {
head->left = createStepsBinaryTree(head->left, newStepsInt, x, y);
}else{
head->right = createStepsBinaryTree(head->right, newStepsInt, x, y);
}
}
return head;
}

这就是我从另一个递归函数调用此函数的方式:

Coor insertDataToTree(Node stepsTree,Coor root, int x, int y, int map[length][length], int steps){

steps++;
stepsTree = createStepsBinaryTree(stepsTree, steps, x, y);
.
.
.

这就是我将其输入递归函数的方式:

Node stepsTree = NULL;

root = insertDataToTree(stepsTree,root, startPoint.x, startPoint.y, map, startPoint.steps);

现在我遇到的主要问题是:它在前两次运行中运行良好,但随后它第三次运行该树中的两个结构,但是当它应该给自己一个 NULL 结构时,它会给出一些非常接近 NULL 的东西。它显示(节点*)0x000000000000000000001。

有谁知道我怎样才能阻止这种疯狂? :)

最佳答案

正如 @wildplasser 所指出的,您为 Node(指针类型)分配了足够的空间。您要么需要更改代码,使 Node 成为一个结构体,要么在 malloc 中分配 sizeof(struct node) 字节。

我强烈建议您不要在 typedef 中隐藏指针 - 这是导致问题的几个示例之一。

关于c - 结构体递归内存处理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17253252/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com