Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Best way to compare 2 arrays ?

Status
Not open for further replies.

user2base

Technical User
Oct 16, 2002
29
GB
What is the best way to check if 2 arrays are the same ??
(i.e contain exactly the same values)
 

Hi,
The Arrays don't contain any filler space you can use memcmp. However if the compiler has introduced filler space like

struct {
char c;
/* compiler will add a char filler[3]; */
int i;
}

where there are 3 unused bytes in your structure, there is no way to gaurentee the value of those 3 bytes and therefore memcmp can't be used.

However if you ZERO fill your structure before you fill it in so you know those FILLER bytes are zero then you can use MEMCMP again.

MEMCMP is optimized to fail when it reachs the first different value.

Without using MEMCMP the only way is to compare every field.


----
 
Hi,
Please ignore that post. I was posting to the wrong forum. Sorry.
 
Here is a way to compare two simple arrays.
Code:
#!perl
# comparing two simple arrays
@one = ('a','e','c','d');
@two = ('a','b','c');

for ($i = 0; $i < ((@one > @two) ? @one : @two); $i++)
    {
    unless ($one[$i] eq $two[$i]) 
        {
         print &quot;SLOT: $i \n  V1: $one[$i]\n  V2: $two[$i]\n&quot;;
        }
    }
'hope this helps

If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
 
I posted a reply for comparing two arrays using a hash before. you can see it here:
thread219-388605 use this method if you want to match irrespective of the order of elements) ---
cheers!
san.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top