Best way to compare two int arrays of the same length?

38,530

Solution 1

Use the standard memcmp function from <string.h>.

memcmp(a, b, sizeof(a)) == 0

whenever a and b are equal.

Solution 2

If you mean

int a[] = {0,1,0,0,1};
int b[] = {0,1,0,0,1};
int c[] = {1,1,0,0,1};

then

memcmp(a, b, sizeof(a)); /* returns zero for a match */
memcmp(a, c, sizeof(a)); /* returns nonzero for no match */

Solution 3

Use a loop and compare the individual elements one after another.

Share:
38,530
user1083734
Author by

user1083734

Updated on July 01, 2022

Comments

  • user1083734
    user1083734 almost 2 years

    what is the best way to compare int arrays b and c with a:

    int a[] = {0,1,0,0,1};
    int b[] = {0,1,0,0,1};
    int c[] = {1,1,0,0,1};
    

    b and c are just examples, assume they can be any combination of 0s and 1s.

    I am trying to detect arrays identical to a. I have googled this for a while and have not found a satisfactory answer.

    This is a beginners question I realise, thank you for your patience.

  • J. C. Salomon
    J. C. Salomon over 12 years
    Minor note: If there are padding bits in the int type, memcmp() may yield a false negative. Fortunately, the OP is unlikely to run across such implementations.
  • einpoklum
    einpoklum over 9 years
    @J.C.Salomon: What are "padding bits in the int type"?
  • this
    this over 8 years
    Using memcmp in this case in C is not reliable because of possible padding bits.
  • this
    this over 8 years
    Using memcmp in this case in C is not reliable because of possible padding bits.
  • Useless
    Useless over 8 years
  • this
    this over 8 years
    @Useless That is true, but it is also a red herring. I was talking about padding bits in integers themselves.
  • Useless
    Useless over 8 years
    You think there are secret un-initialized bits inside an int? Perhaps you could give an actual example of what you mean - in fact, ideally ask (and answer, if you like) a question rather than continuing this in comments.
  • Wim
    Wim over 8 years
    don't forget to escape the loop when you reach the end of one of the arrays, in case the size is different
  • supercat
    supercat about 8 years
    @Useless: Some machines (especially DSPs) have an accumulator whose size is a not a multiple of a memory word [one might have a 16-bit memory word but a 40-bit accumulator]. In some cases, it may be helpful for them to define a type whose useful portion is not a multiple of the word size [e.g. such a platform could define "long" as three bytes long, but with only 40 bits holding useful information].