Karl Neumann
Karl Neumann

Reputation: 103

My array has the wrong values

I'm working my way through C++ Primer Plus by Stephen Prata. Please Help! My program reads 10 or less int values( golf scores) into an array then calls a function to print out the values and the average. I have used the code::blocks debugger as best I can. I get the proper value into the area by prompting via the input function but when I return a *int ptr to the display function the values are different when I print them out. I suspect my use of pointers is incorrect since I am just learning about them. If anyone sees any obvious errors on my part, I would be most grateful if you point them out. I've been at this for too long and I'm lost. Here is all the code:

#include <iostream>

using namespace std;

const int SIZE = 10;

int* input()
{
    int scores[10] = {0};

    int score = 0;

    for(int i = 0; i < SIZE; i++)
    {
        cout << "Enter golf score: " << endl;
        if(cin >> score)
        {
              scores[i] = score;
        }
        else
            break;

    }
    return scores;
}

float average(int* p_ints)
{
    float sum = 0;
    int i = 0;
    while(p_ints[i] != 0 && i < SIZE)
    {
        sum += float(p_ints[i]);
        i++;
    }
    return sum/i;
}

void display(int* p_ints)
{
    cout << "scores: ";
    int i = 0;
    while(p_ints[i] != 0 && i < SIZE)
    {
        cout << p_ints[i] << " ";
        i++;
    }
    cout << "average: " << average(p_ints) << endl;
}



int main()
{
    int* p_ints = input();
    display(p_ints);
    return 0;
}

Upvotes: 1

Views: 2049

Answers (1)

vsoftco
vsoftco

Reputation: 56547

Your problem is that input() returns a pointer to a locally constructed object

int scores[10] = {0};

// ...

return scores; // PROBLEM HERE, scores goes out of scope and its memory re-claimed by the OS

When you exit from the function input, scores is out of scope and you end up with a so-called dangling pointer.

So, either allocate memory dynamically for scores,

int* scores = new int[10]{0}; // this memory is not being automatically reused by the OS at exit from the function

and don't forget to delete[] the returned pointer after usage, or (better) pass the pointer scores (of which memory you want to fill) to the function input as a parameter

void input(int* scores) // pass a pointer to the output array

Or, better yet, use standard C++ containers like std::vector.

Upvotes: 5

Related Questions