【问题标题】:Passing BST to struct array将 BST 传递给结构数组
【发布时间】: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


【解决方案1】:

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

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

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);

很遗憾,我无法测试它,但我认为它应该可以工作。

附:抱歉所有的编辑/删除。我看错了什么。

【讨论】:

  • 是的,确实如此。感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多