0

I'm trying to concatenate two arrays that were initialized from file input into one dynamic array and returning it to an output file but while testing I found out that the returned dynamic array is initialized with random numbers. I'm sorry for my lack of experience as I am a beginner.. These are my input text files

Input1.txt

1
2
3

Input2.txt

4
5
6

and this is my code ..

#include <iostream>
#include <fstream>

using namespace std;

int * concatenate(int *a1,int *a2,int size);

int main() {
    int size = 3;
    int arr1[size];
    int arr2[size];
    ifstream fin;
    ofstream fout;
    fin.open("input1.txt");
    for(int i = 0; i < size; i++) {
        int value;
        fin>>arr1[i];
        cout<<arr1[i]<<endl;
    }
   fin.close();
    
    fin.open("input2.txt");
    for(int j = 0; j < size; j++) {
        fin>>arr2[j];
        cout<<arr2[j]<<endl;

    }
   
    int *arr3 = concatenate(arr1,arr2,size);
    cout<<arr3[1];

    return 0;
}

int * concatenate(int *a1,int *a2,int size) {
    int * r = new int[size*2];
    for(int i = 0; i > size*2; i++) {
        if(i < size)
            r[i] = a1[i];
        else
            r[i] = a2[i-size];
    }
    return r;
    
}
1201ProgramAlarm
  • 32,384
  • 7
  • 42
  • 56
  • Voted to close as a typo. Loop condition in `concatenate()` is `i > size*2` - the `<` operator needs to be used instead of `>` – Peter Dec 07 '21 at 23:01

2 Answers2

2

If you're using c++ you should consider using vectors instead of arrays. They make operations like these way easier.

Here's for reference:

You can referer to this post to see how to concatenate two vectors. Concatenating two std::vectors

If you want to stick to your method there's an error in your concatenate function.

You never actually enter the for-loop since your condition for stopping is wrong. The condition in your loop is continue iterating while i > size * 2 but, with i = 0 at the start, that will never be true thus you will never enter the loop. You can fix this just by inverting the comparaison like so i < size * 2.

To avoid this kind of errors you can try to setup a debugger and go through your code line by line seeing the values of variables and what lines are actually executed. This method will help you catch a lot of small mistakes like these.

As for the random values in your return array it's because C and C++ don't clean the memory being allocated by your program when creating a new array or calling malloc for example.

Seïfane Idouchach
  • 620
  • 2
  • 5
  • 21
1

you seem to have a small typo in your code in the last for loop,

for(int i = 0; i > size*2; i++)

i think you ment (watch the comparison sign)

for (int i = 0; i < size*2; i++)

you can try to cout values from the code you think doesn't work, or even better, use an IDE like Visual studio to debug your code when it fails for no apparent reason, which allows you to see your code executing line by line in the future.

Ahmed AEK
  • 8,584
  • 2
  • 7
  • 23