comparing arrays

I want to ascertain whether two byte arrays of equal size contain the same data. It seems that a simple (array1 == array2) won’t work, although this may be the fault of bugs elsewhere. Assuming this doesn’t work, do I need to loop through and do a byte by byte comparison, or is there a more elegant way?

Cheers,
Dan

It seems that a simple (array1 == array2) won't work,

Nope.

although this may be the fault of bugs

No, that's the way the language is designed. The name of an array is a pointer to the first element in the array. With the expression array1 == array2 You are comparing two addresses, and since they're different arrays this will always be false.

do I need to loop through and do a byte by byte comparison

Yep.

-j

Hi Dan,

I want to ascertain whether two byte arrays of equal size contain the same data. It seems that a simple (array1 == array2) won't work, although this may be the fault of bugs elsewhere. Assuming this doesn't work, do I need to loop through and do a byte by byte comparison, or is there a more elegant way?

Yes, you have to go through all the Elements. If these two arrays here [1,2,3] and [3,2,1] are also equal in you understanding it's even more complex as you have to check every element in the first array for wether it exists in the second array.

That would even require a double loop.... Eberhard

Its not elegant, but you can use the memory compare function, memcmp to check if two arrays of the same size have the same data.

If array1 and array2 are the names of the arrays and the size in bytes is ARRAY_SIZE then:

if( memcmp(array1, array2,ARRAY_SIZE) == 0) Serial.println(“the array contents are the same”);

Which method uses less resources?

Cheers,
Dan

Dan, I would think there would be little difference because the memcmp library function would use similar machine code to what the compiler would produce if you wrote an efficient loop comparing elements. If you want to see exactly how much program space and RAM the two techniques use, you could try each in sketch and look at the program memory usage. You can find the RAM usage using a function documented here: http://www.arduino.cc/playground/Code/AvailableMemory

memcmp is the loop testing all elements of the arrays encapsulated in a function call.

That's cool. I am not running tight against memory constraints at the moment, so if they're probably pretty similar then I may as well just stick with my loop. I might have a bit of an experiment out of curiosity, though; if I do I shall report back!

Thanks for your advice, Dan