在 c++ 中的函数中动态分配数组
Dynamically allocating array in a function in c++
在我正在处理的项目的一部分中,我正在实现一个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]
正确插入。
请帮我看看我做错了什么:(
我不确定这是否是您的所有问题,但是您正在按值传递i,并且需要通过引用传递以了解如何使用它。
void KeyIntoArrByData(AVL_node<Dat,Key,OS>* root, Key** array, int &i)
相关文章:
- 这是使用回溯的 nqueen 问题,但我使用了动态 2d 数组,我的程序编译良好,但不返回任何输出
- 动态更改数组的大小并读取值.(无矢量)
- 检测到堆损坏:在正常块 c++ 动态 2D 数组之后
- 动态维度数组的 C++ 别名指针
- C++ 在析构函数调用之前删除的动态成员数组
- 从类 c++ 动态创建数组
- 具有静态 std::array 的神经网络比使用动态 C 数组的神经网络慢
- "Error reading character of string" 为哈希动态增长数组的问题 (C++)
- 为什么我们在传递动态 2D 数组时不需要列数?
- 如何解决在使用动态 2D 数组进行矩阵乘法的 MPI 进行并行编程时的问题
- 使用动态布尔数组时出现问题
- C++ 在类中删除动态 2D 数组时不断"Aborted (core dumped)"
- 如何在C 中动态输入数组
- 关于删除动态对象数组
- 在C 中动态更改数组大小
- 使用动态指针数组进行动态对象分配 - 使用什么删除?
- 动态字符串数组分配错误
- 函数中的动态 2D 数组分配并将其返回给主数组
- c++动态字符串数组分配
- 使用字符串或字符动态分配(数组)