function returning array problem (c++)

Started by
3 comments, last by jkeppens 21 years, 7 months ago
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?
Advertisement
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.
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]
quote:Original post by jkeppens
int* values = new int[2]; // changed
...
delete f; //added
Should be "delete[] f"
oops, missed that one ;-)

This topic is closed to new replies.

Advertisement