1

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; } 

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I wouldn't go for the new just yet. Pass the function an array, or return a vector or something. With that SIZE variable there are a lot of options. Also, +1.
@keyser agree, I would pass the array directly (actually, I would return a std::vector ;) )
It makes sense now. I see the error pertaining to the dangling pointer. Thanks.
@user3713343 something to remember: never return a pointer that refer to an object that is stack-allocated like Foo foo; return &foo; //oops. Such stack-allocated objects cease to exist at the exit from the function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.