-3

I have a function declared like this

int * return_array(int * arr1 , int * arr2); 

and the function is defined like this

int * return_array(int * arr1, int * arr2) { int arr_sum[5]={0}; int count = 0; do { arr_sum[count] = *(arr1+count)+*(arr2+count); count ++; } while (count < 5); return (arr_sum); } 

this is how i am trying to access the returned array in the main function

int *get_arr; get_arr=return_array(arr1,arr2); cout << "Their sum is :" << endl; for (count = 0; count < 5; ++count) { cout << *(get_arr+count) << endl; } 

the first sum is correct but the rest looks to be garbage values, what might be the cause?

1
  • 2
    Consider using, and return, std::array<int, 5> Commented Nov 10, 2014 at 16:07

2 Answers 2

1

You are returning an array from a function, but its scope does not go outside that function, so I'm sure you are seeing "garbage values".

You need to either allocate the space for arr_sum yourself in the function, or you can pass an array to be filled from the caller.

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

Comments

0

You are getting garbage as you are trying to return something local to function,

return (arr_sum); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.