Archived

This topic is now archived and is closed to further replies.

function returning array problem (c++)

This topic is 5587 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, I''ve got a function that returns an array of 2 ints. When I check the array in the function it displays the values correctly. When I call the function and display the 2 values then, I get wrong data. The first value is correct, but the seconds seems to resemble an address. Maybe I did something wrong?
  
#include <iostream>
using namespace std;

int *test() {
   int values[] = {1, 1};
   cout << values[0] << ", " << values[1] << endl;  // displays 1,1

   return values;   // return &values[0] gives the same error

}

int main(int argc, char* argv[]) {
   int* f = test();
   cout << f[0] << ", " << f[1] << endl;
   cin.get();
   return 0;
}
  
Outcome :
  
1, 1
1, 4200745
  
Does anyone see the problem?

Share this post


Link to post
Share on other sites
quote:
Original post by jkeppens
I''ve got a function that returns an array of 2 ints.

You can''t have. It''s not possible!
quote:

Maybe I did something wrong?

Yes, you''re returning a pointer to a local variable. When the function returns, the pointer is left dangling, and dereferencing it leads to undefined behaviour. This is just one of the ways in which C++ arrays are evil.

Share this post


Link to post
Share on other sites
This seems to work, is this okay?


  

#include <iostream>

using namespace std;

int *test() {
int* values = new int[2]; // changed

values[0] = 1;
values[1] = 1;
cout << values[0] << ", " << values[1] << endl; // displays 1,1

return values;
}

int main(int argc, char* argv[]) {

int* f = test();
cout << f[0] << ", " << f[1] << endl;
delete f; //added


cin.get();
return 0;
}


[edited by - jkeppens on August 28, 2002 5:27:19 AM]

[edited by - jkeppens on August 28, 2002 5:28:03 AM]

Share this post


Link to post
Share on other sites