-1

I've been trying to do a little program which allows the user to enter 5 numbers each (out of 2 arrays). Once that is done, there should be a function that compares the [i] number of both arrays and puts the bigger one in the 3rd array.

e.g array1[0] = 2; array2[0] = 5

That will result in array3[0] = 2.

Tried using the functions to achieve it, but for some reason, the result of all array3[i] numbers is equal to 5.

Here's my code:

#include <iostream>

using namespace std;

int array1[5], array2[5], array3[5];

void insert(int[], int);
float initialization(int[], int[], int[], int);


int main()
{
    const int size = 5;

    insert(array1, 5);
    cout << endl;
    insert(array2, 5);

    for (int i = 0; i < size; i++)
    {
        cout << "The " << i + 1 << ". number of the 3rd array is: " << initialization(array1, array2, array3, size) << endl;
    }

    system("PAUSE");
    return 0;
}

void insert(int array[], int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << "Enter the " << i + 1 << ". number of the array: ";
        cin >> array[i];
    }
    cout << "\n";
}

float initialization(int array1[], int array2[], int array3[], int size)
{
    int r;
    for (int i = 0; i < size; i++)
    {
        r = i;
        if (array1[i] < array2[i])
        {
            array3[i] = array1[i];
        }
        else
        {
            array3[i] = array2[i];
        }

    }

    return array3[r];
}

Any help?

TheDoomDestroyer
  • 2,434
  • 4
  • 24
  • 45

1 Answers1

3

In function initialization, the value of r is always 5 when you return array3[r].

This is not even a valid memory access (i.e., array3[5] is UB).

Get rid of this return statement, and in the main function simply do:

initialization(array1, array2, array3, size);
cout << "The " << i + 1 << ". number of the 3rd array is: " << array3[i] << endl;
goodvibration
  • 5,980
  • 4
  • 28
  • 61