【发布时间】:2016-01-24 22:52:14
【问题描述】:
我想编写一个函数,将BST 中的所有单词和值传递给结构数组。在tree 我有words(node->word) 和value(node->val)。
在main 我声明了pair struct数组。
这是我的代码:
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;
}
调试器说:
访问冲突写入位置 0x0000001。
【问题讨论】:
-
它将始终以正确设置代码的方式返回 Null。
-
这些石灰不会执行 ever.array[index]->val= node->val; // 然后将数据写入数组 array[index]->word = malloc(sizeof(char)*(strlen(node->word)+1)); strcpy(array[index]->word,node->word);索引++; inOrder(node->right, array, index);
-
@Maertin 那么你有什么建议呢?我不知道该怎么做。
-
这里有两个问题。一个是错误处理,另一个是逻辑。您 printF arR.value 所在的行,您需要更正它以仅在 arr[o].val 不等于 null 时打印。一旦你解决了这个问题,你就不会得到你提到的错误。在遍历子节点之前,您还需要先在 inOrder 中进行数组赋值。当经过left child后到达null时,需要遍历回父节点,然后做右节点。我并没有真正用 C++ 编程 - 所以除非我的机器中有合适的 IDE 中的代码,否则我不知道除了逻辑之外我能提供什么帮助
-
@Maertin 也许我遗漏了一些东西,但我看不出那里的代码有什么问题。
inOrder将返回,然后这两行将运行。
标签: c arrays struct binary-search-tree