lundi 21 février 2022

when I call a function it returns a random valued array instead of the "right one" [closed]

I'm trying to improve myself in competitive programming and I'm trying to do a easy task in a hard way. I'm trying to split an array in two arrays (even and odd positions), apply the QuickSort on each of the two and then putting them together once again.

But I have some wrong output, probably I'm getting something wrong with pointers.

int arr[5] = {5, 4, 1, 3, 2};
int** a;
int size = sizeof(arr) / sizeof(arr[0]);
a = makearrs(arr, size);

Here's where I call the function makearrs passing it the array and the fixed size (I could pass 5 but I just calculated it).

Here's the function makearrs

int** makearrs(int* arr, int size){
int size_arr = size / 2;
int even_arr[size_arr + 1];  //[0, 1, 2, 3, 4]
int pair_arr[size_arr + 1];
// Inizializzo
for(int i = 0; i<=size_arr; i++){
    even_arr[i] = 0;
    pair_arr[i] = 0;
}
int j = 0;
for(int i=0; i<size; i = i+2){          //Lettura sicura, va bene per entrambi i casi.
    pair_arr[j] = arr[i];
        if(i+1 != size) {
            even_arr[j] = arr[i + 1];
        }
    j++;
}
int ** a = makepairs(pair_arr, even_arr);
return a;

And finally the function makepairs which creates an array of pointers (two-sized) containing the two arrays (even and odd position array).

int** makepairs(int* arr, int* arr2) {
int** ptr = new int*[2];
ptr[0] = arr;
ptr[1] = arr2;
return ptr;

If I try to for-print the resulting

 int * even;
even = a[1];
int * pair;
pair = a[0];
for(int i=0; i<3; i++){
    cout << even[i];
    cout << "\n";
    cout << pair[i];
    cout << "\n";

I get this output: 4 47398584 1 1 -325478504 47398584

Aucun commentaire:

Enregistrer un commentaire