Reputation: 278
When I run this code I get a bad_alloc error, Am I accessing the subscript operator wrong or something ? To me it makes sense that I go to the appropriate object, it gets returned and then the subscript operator should kick in ? By the way I want to use arrays and not vectors :)
class A{
public:
A(int size)
{
array = new int[size];
}
int& operator[](const int &i)
{
return array[i]
}
private:
int * array;
};
int main() {
A ** a = new A*[10];
for(int i = 0; i < 10; i++) {
a[i] = new A(10);
for(int l = 0; l < 10; l++) {
cout << a[i][l] << endl;
}
}
}
Thanks in advance
Upvotes: 0
Views: 97
Reputation: 7858
You need to dereference the pointer before you can call operator[]
cout << (*(a[i]))[l] << endl;
Here's what needs to happen, step by step:
A* pA = a[i];
A& rA = *pA;
int& val = rA[l];
cout << val;
Currently this happens:
A* pA = a[i];
A& ra = *(pA + l); // pA is indexed as an array of As - this is wrong
cout << ra; // invalid memory
Upvotes: 3