gpt4 book ai didi

c - 将 BST 传递给结构数组

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

我想编写一个函数,将所有单词和值从 BST 传递到结构数组。在 tree 中,我有 words(node->word)value(node->val)
main 中,我声明了pair结构体的数组。

这是我的代码:

void inOrder(Tree *node,pair *array[], int index)
{
if(node == NULL){ // recursion anchor: when the node is null an empty leaf was reached (doesn't matter if it is left or right, just end the method call
return;
}
inOrder(node->left, array, index); // first do every left child tree
array[index]->val= node->val; // then write the data in the array
array[index]->word = malloc(sizeof(char)*(strlen(node->word)+1));
strcpy(array[index]->word,node->word);
index++;
inOrder(node->right, array, index); // do the same with the right child
}

int main(int argc, char *argv[])
{

Tree *myTree = NULL;
pair arr[5000];
int index=0;
...
inOrder(myTree,&arr,index);
printf("%d",arr[0].val);
zero(myTree);
return 0;
}

调试器说:

Access violation writting location 0x0000001.

最佳答案

这里的指针有些奇怪。您的 inOrder 函数头需要一个 pair 指针数组,但您传入了一个指向 pair 数组的指针(这实际上只是一个随机内存块)。我很确定这就是指针错误的来源。

解决这个问题的方法有很多,但我只介绍我最喜欢的一个。为什么要将指针传递给指针而不仅仅是指针?尝试更改您的函数 header :

void inOrder(Tree *node, pair *array, int index)

并访问这样的内容:

array[index].val= node->val;   // then write the data in the array
array[index].word = malloc(sizeof(char)*(strlen(node->word)+1));
strcpy(array[index].word,node->word);

并从main调用它,如下所示:

inOrder(myTree,arr,index);

不幸的是,我无法测试它,但我认为它应该有效。

附注对所有的编辑/删除表示抱歉。我误读了一些内容。

关于c - 将 BST 传递给结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34982552/

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