tags:

views:

395

answers:

4

I am trying to compare two int arrays, element by element, to check for equality. I can't seem to get this to work. Basic pointer resources also welcome. Thank you!

int *ints;
ints = new int[10];

bool arrayEqual(const Object& obj)
{
    bool eql = true;

    for(int i=0; i<10; ++i)
    {
     if(*ints[i] != obj.ints[i])
      eql = false;
    }

    return eql;
}
+14  A: 
Beh Tou Cheh
Counternote: It just requires the latter range to have _at least_ as many as the first.
Marcus Lindblom
CounterCounterNote: You are absolutely correct.
Beh Tou Cheh
A: 

I assume this is all wrapped by "class Object {" and "}"?

Just remove the "*" and it should work.

Keith Randall
+1  A: 

I'm surprised nobody's asked why you're using arrays in the first place. While there are places that arrays can be hard to avoid, they're few and far between. Most of your code will normally be simpler using std::vector instead. Since std::vector overloads operator==, all you have to do in this case is something like if (a==b) ... Even in the few places that vector isn't suitable, TR1::array will often do the job (and IIRC, it provides an overload of operator== as well).

Jerry Coffin
A: 

When you do if(*ints[i] != obj.ints[i]), what you are comparing is the address pointed by ints[i] with the content of obj.ints[i], instead of the content of ints[i] itself. That is because the name of an array is already a pointer to the first element of an array, and when you add the subscript, you will look for the ith position after the first in that array. That's why you don't need the *.

The correct is:

int *ints;
ints = new int[10];

bool arrayEqual(const Object& obj)
{
    bool eql = true;

    for(int i=0; i<10; ++i)
    {
        if(ints[i] != obj.ints[i])
                eql = false;
    }

    return eql;
}

Hope I helped!

jpmelos