c - 将 BST 传递给结构数组

标签 c arrays struct binary-search-tree

我想编写一个函数,将所有单词和值从 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/

相关文章:

c - 取消引用三重指针

c - 为 Windows 编写正确的 Ansi C makefile

java - if for 循环抛出自定义异常

c - 从函数将值分配给全局结构

C 数据结构错误

c - 如何将这个 C 程序变成一个计算每行之和及其总和的函数?

c - C语言中逐行读取文本文件

Java - 写入文件的缓冲区的长度

java - 具有不同数组参数的构造函数 java

c - 初学者从结构数组中删除第一个元素 (C)