Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing multi-dimensional array element c++

I am trying to work with a multi-dimensional array in MSVS2010 console application, and I need to access members of a 2D array. I instantiate the array as

Thing::Thing(int _n){
    // size of the array
    this.m = _n;
    thing = new int*[m];
    for(int ii = 0; ii < m; ii++){
        thing[ii] = new int[m];
    }
}

this is working fine. though when I go to do a operator=, or operator== that both use the similar structure of:

Thing& Thing::operator=(const Thing & _thing){
    for(int ii = 0; ii < m; ii++){
        for(int jj = 0; jj < m; jj++){
            thing[ii][jj] = _thing[ii][jj]; //error thrown on this line
        }
    }
    return *this;
}

this throws 2 errors

binary "[": 'const Thing' does not define this operator or a conversion to a type acceptable to the predefined operator
IntelliSense: no operator"[]" matches these operands

this doesn't make sense as it is an array of type int, and the "[]" operators have not been altered not to mention that error highlighting only puts it under:

_thing[ii][jj];

I can kinda live without the assignment operator, but I need the comparison operator to have functionality.

like image 670
gardian06 Avatar asked May 03 '26 10:05

gardian06


1 Answers

You should do: thing[ii][jj] = _thing.thing[ii][jj]; in your assignment loop. And you should also check if the array sizes for both (this and _thing) are the same: it may give a crash otherwise.

You get an error because you are trying to use operator[] (indexing operator) on an object class Thing, not on its internal array. If you want to use the Thing class like an array you should define an indexing operator for it e.g.:

int* Thing::operator[](int idx)
{
   return thing[idx];
}
like image 52
sirgeorge Avatar answered May 05 '26 23:05

sirgeorge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!