JosephTLyons
JosephTLyons

Reputation: 2133

Function returns Array but output is not as expected

The issue I'm having is I'm trying to return an array from the function EnterNumber() and display it in the main, but its coming out fairly crazy. I went through with the debugger and the numbers are correct in the debugger, just not correct in once it prints to the screen.

Here's a shot of the debugger after returning from the function

Here's a shot of what it prints

I realize there's a global const int in my program, but it was sanctioned by my professor who wanted us to do it just this time for this program.

Just looking for a nudge on why its printing incorrectly. Thank you.

#include <iostream>

using namespace std;

void EnterNumber(int Number[]);

const int SIZE=20;

int main()
{
    int LargeNumber1[SIZE];
    int LargeNumber2[SIZE];

    for (int Counter1=0; Counter1<=19; ++Counter1)//zeros arrays out
    {
        LargeNumber1[Counter1]=0;
        LargeNumber2[Counter1]=0;
    }

    EnterNumber(LargeNumber1);

    for (int Counter2=0; Counter2<=19; ++Counter2)//display array 1 contents
    {
        cout << LargeNumber1[SIZE];
    }

    cout << "\n\n";

    EnterNumber(LargeNumber2);

    for (int Counter2=0; Counter2<=19; ++Counter2)//display array 2 contents
    {
        cout << LargeNumber2[SIZE];
    }

}

void EnterNumber(int Number[])
{
    int TemporaryArray[SIZE];
    int PlaceCounter;

    char Storage;

    PlaceCounter=0;

    for (int Counter1=0; Counter1<=19; ++Counter1)//zeros arrays out
    {
        TemporaryArray[Counter1]=0;
        Number[Counter1]=0;
    }

    cout << "Please enter a large number --> ";

    cin.get(Storage);

    while (Storage!='\n' && PlaceCounter<SIZE)//puts number in temp array - left aligned
    {
        TemporaryArray[PlaceCounter]=(Storage-'0');
        ++PlaceCounter;
        cin.get(Storage);
    }

    --PlaceCounter;//decrement one to get it to work properly with element style counting, else, extra zero at end

    for (int A=SIZE-1; PlaceCounter>=0; A--, PlaceCounter--)//transfers old array into new array, right aligned
    {
        Number[A]=TemporaryArray[PlaceCounter];
    }

    cout << "\n";
}

Upvotes: 1

Views: 39

Answers (1)

user3386109
user3386109

Reputation: 34839

This:

for (int Counter2=0; Counter2<=19; ++Counter2)
{
    cout << LargeNumber1[SIZE];
}

should be this:

for (int Counter2=0; Counter2<SIZE; ++Counter2)
{
    cout << LargeNumber1[Counter2];
}

You were repeatedly printing a number that was just beyond the end of the array.

Upvotes: 2

Related Questions