将BST传递给struct数组

时间:2016-01-24 22:52:15

标签: c arrays struct binary-search-tree

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

这是我的代码:

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。

1 个答案:

答案 0 :(得分:1)

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

有很多方法可以解决这个问题,但我会把我最喜欢的方法解决。您之所以将指针传递给指针而不仅仅是指针的原因是什么?尝试更改功能标题:

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

不幸的是,我无法对其进行测试,但我认为它应该可行。

P.S。抱歉,所有的编辑/删除。我误读了一些东西。