gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

Beginners > general c++ question, comparing arrays

#12475 - yaustar - Sat Nov 15, 2003 5:52 pm

is it possible to compare two arrays of same type and length by doing:
Code:

if(array1 == array2)

_________________
[Blog] [Portfolio]

#12477 - abilyk - Sat Nov 15, 2003 6:30 pm

No, that's comparing the pointers of the two arrays. I assume from your question that you'd be comparing arrays that each have their own memory location, so that would always return false. Instead, you'll need to write a function that compares all the elements of the arrays.

Some pseudocode:

Code:

u16 Equals(array1, array2, length_of_both_arrays)
{
   u16 comparison = 1;  // true

   for(int i = 0; i < length_of_both_arrays, i++)
      if(array1[i] != array2[i])
         comparison = 0; // false

   return comparison;  // returns 1 for true, 0 for false
}

#12479 - yaustar - Sat Nov 15, 2003 7:33 pm

thanks.
_________________
[Blog] [Portfolio]

#12494 - col - Sun Nov 16, 2003 1:57 am

abilyk wrote:
No, that's comparing the pointers of the two arrays. I assume from your question that you'd be comparing arrays that each have their own memory location, so that would always return false. Instead, you'll need to write a function that compares all the elements of the arrays.

Some pseudocode:

Code:

u16 Equals(array1, array2, length_of_both_arrays)
{
   u16 comparison = 1;  // true

   for(int i = 0; i < length_of_both_arrays, i++)
      if(array1[i] != array2[i])
         comparison = 0; // false

   return comparison;  // returns 1 for true, 0 for false
}


the above is functionally correct, but
if you shuffle it around a little it can be much more efficient:
Code:

  for(int i = 0; i < arrayLength, ++i){
      if(array1[i] != array2[i]){
          return 0;
      }
      return 1;
  }


cheers

col

#12500 - abilyk - Sun Nov 16, 2003 5:10 am

col wrote:
the above is functionally correct, but
if you shuffle it around a little it can be much more efficient:

cheers

col


Heh, yeah, that is more efficient, isn't it? Thanks for pointing that out. =D

#12507 - sajiimori - Sun Nov 16, 2003 6:41 am

Quote:

Heh, yeah, that is more efficient, isn't it?

Well, only if by 'efficient' you mean 'wrong'. The given code will return true even if only the first elements of the arrays are the same! :-D

#12512 - tepples - Sun Nov 16, 2003 1:55 pm

Would this be any more correct?
Code:

for(int i = 0; i < arrayLength, ++i){
  if(array1[i] != array2[i]){
    return 0;
  }
}
return 1;

_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.

#12515 - tom - Sun Nov 16, 2003 3:16 pm

tepples wrote:
Would this be any more correct?


yes, but what about using memcmp() ?