将 BST 传递给结构数组
Passing BST to struct array
我想编写一个函数,将 BST
中的所有单词和值传递给结构数组。在 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;
}
调试器说:
Access violation writting location 0x0000001.
这里的指针有点奇怪。您的 inOrder
函数 header 需要一个 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);
不幸的是,我无法测试它,但我认为它应该可以工作。
P.S。对不起所有 edits/deletions。我看错了。
我想编写一个函数,将 BST
中的所有单词和值传递给结构数组。在 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;
}
调试器说:
Access violation writting location 0x0000001.
这里的指针有点奇怪。您的 inOrder
函数 header 需要一个 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);
不幸的是,我无法测试它,但我认为它应该可以工作。
P.S。对不起所有 edits/deletions。我看错了。