【发布时间】:2014-12-01 00:17:32
【问题描述】:
在我正在处理的项目的一部分中,我正在实现 AVL 树。我需要实现的功能之一是接收和 Key 数组(树键的模板类)和一个 int 指针(我需要在其中插入 AVL 树的大小)。在这个函数中,我需要以一定的顺序将树的元素插入到数组中(现在没关系)。
这是函数的签名,它必须是这样的:GetAllAppsByDownloads(Key **apps, int *numOfApps)
但由于某种原因,我未能实现它。我遇到了一些问题,主要问题是显然我分配的内存不正确(我希望数组初始化为 Key 的默认值),然后当我插入键时,它们没有正确插入。
这就是我从我构建的测试中调用函数的方式(也许我做错了?):
int* keyArr;
int numApps;
tree.GetAllAppsByData(&keyArr,&numApps);
for(int i=0; i<numApps; i++){
cout<<keyArr[i]<<endl;
}
这些是我的功能:
void GetAllAppsByData(Key** apps, int*numOfApps){
AVL_node<Dat,Key,OS>* temp=(getRoot());
*numOfApps=size;
*apps=(new Key[size]()); /*size represents the amount of elements.
its a variable in the private section of the class*/
KeyIntoArrByData(temp, apps, 0);
};
void KeyIntoArrByData(AVL_node<Dat,Key,OS>* root, Key** array, int i){
if(root==NULL) return;
KeyIntoArrByData(root->right, array, i);
array[i]=&(root->key);
i++;
KeyIntoArrByData(root->left, array, i);
}
/* P.S Dat and OS are other template variables I receive from the user, they
don't matter here*/
我认为密钥插入不正确的原因是因为i 在我从递归中返回时发生了变化,但我没有找到解决方案(我尝试将另一个 int 添加到我将只使用的类中在这个函数中,所以当递归返回时它将保持为新值),不介意在这里给一些帮助哈哈。
但这不是大问题,它插入数组的元素插入不正确(放入垃圾而不是键),注意:只有array[0] 插入正确。
请帮我看看我做错了什么:(
【问题讨论】:
-
如何使用调试器来逐步了解实际情况?
-
*numOfApps=size;size究竟来自哪里? -
不要推测,使用调试器单步调试代码并找出到底发生了什么。
-
@πάνταῥεῖ ῥεῖ:每次我插入一个元素时,我都会增加大小(
size++;),当我删除一个元素时,我会减少大小(size--;)。它在构造函数中初始化为0。 (@Captain Obvlious)我确实使用了调试器,但我不明白到底出了什么问题。它正确地做每一件事,但突然崩溃或将垃圾放入数组而不是应该插入的东西。另外,它似乎没有使用*apps=new Key[size]()中的默认构造函数初始化数组,这是为什么呢?
标签: c++ arrays argument-passing dynamic-allocation