在 c++ 中的函数中动态分配数组

Dynamically allocating array in a function in c++

本文关键字:动态分配 数组 函数 c++      更新时间:2023-10-16

在我正在处理的项目的一部分中,我正在实现一个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)