Reference to array pointer issue

Hi

I have a problem with a private class member which is a const reference to array. Here is the class:

class SortResult {
friend ostream &operator<<(ostream &out, const SortResult &sr);
public:
SortResult(DataArray &da, DataSorter &ds, const int *&sorted);
private:
DataArray &da;
DataSorter &ds;
const int *&sorted; // The member who has the problem
};

SortResult::SortResult(DataArray &da, DataSorter &ds, const int *&sorted)
: da(da), ds(ds), sorted(sorted) {}

1 ostream &operator<<(ostream &out, const SortResult &sr)
2 {
3 out << sr.ds.get_name() << endl;
4 out << "Barometer: " << sr.ds.get_barometer() << endl;
5 out << "Data: ";
6
7 for (int i = 0; i < sr.da.get_length(); i++)
8 out << sr.sorted[i] << " ";
9
10 return out;
11 }

I used MS Visual Studio 2010 to build the project

The problem occurs when I print an instance of object, which is the friend operator << method. When I used MS Visual debugger, the problem is at line 8. The pointer has invalid address 0xcccccccc which causes a memory violation.

I set a break point to the line where I initialize the object, and all members are initialized correctly:

int *sorted = ds->sort(da.get_data(), da.get_length());
const int *csorted = const_cast<const int *>(sorted);

--> SortResult *dr = new SortResult(da, *ds, csorted);

I don't understand what's wrong. Any comments or suggestions is welcome

Thanks in advance


You're storing a reference to a pointer which isn't sticking around. Storing the pointer by value would probably be more appropriate.
Topic archived. No new replies allowed.