Dynamically allocating array in a function in c++

102 Views Asked by At

In a part from a project I'm working on I'm implementing an AVL tree. One of the functions I need to implements receives and array of Key (template class for the tree's keys) and an int pointer (to which I need to insert the size of the AVL tree). In this func I need to insert the tree's elements into the array in a certain order (doesn't matter now). This is the function's signature and it MUST be like this: GetAllAppsByDownloads(Key **apps, int *numOfApps)

But from some reason I fail to implement it. I encountered few problems and the main one is that apparently I allocate the memory incorrectly (I want the array initialized to the default value of Key) and then when I insert the keys they are not being inserted correctly.

This is how I call the function from the tests I built (maybe I'm doing this incorrectly?):

    int* keyArr;
    int numApps;
    tree.GetAllAppsByData(&keyArr,&numApps);
    for(int i=0; i<numApps; i++){
        cout<<keyArr[i]<<endl;
    }

And these are my functions:

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 think the reason the key are being inserted incorrectly are because i changes when I go back up from the recursion but I failed to find a solution to it (I tried adding another int to the class that I will use only in this func so then it will remain as the new value when the recursion goes back up), wouldn't mind some help here to haha.

But that's not the big problem, the elements it does insert to the array are inserted incorrectly (puts in junk and not the keys), note: only array[0] is inserted correctly.

Please help me see what I'm doing wrong :(

1

There are 1 best solutions below

1
On

I'm not sure if it's all of your problems, but you are passing i by value, and needs to be passed by reference for how your using it.

void KeyIntoArrByData(AVL_node<Dat,Key,OS>* root, Key** array, int &i)