Comparing arrays for equality in C++

138,843

Solution 1

if (iar1 == iar2)

Here iar1 and iar2 are decaying to pointers to the first elements of the respective arrays. Since they are two distinct arrays, the pointer values are, of course, different and your comparison tests not equal.

To do an element-wise comparison, you must either write a loop; or use std::array instead

std::array<int, 5> iar1 {1,2,3,4,5};
std::array<int, 5> iar2 {1,2,3,4,5};

if( iar1 == iar2 ) {
  // arrays contents are the same

} else {
  // not the same

}

Solution 2

Since nobody mentioned it yet, you can compare arrays with the std::equal algorithm:

int iar1[] = {1,2,3,4,5};
int iar2[] = {1,2,3,4,5};

if (std::equal(std::begin(iar1), std::end(iar1), std::begin(iar2)))
    cout << "Arrays are equal.";
else
    cout << "Arrays are not equal.";

You need to include <algorithm> and <iterator>. If you don't use C++11 yet, you can write:

if (std::equal(iar1, iar1 + sizeof iar1 / sizeof *iar1, iar2))

Solution 3

You're not comparing the contents of the arrays, you're comparing the addresses of the arrays. Since they're two separate arrays, they have different addresses.

Avoid this problem by using higher-level containers, such as std::vector, std::deque, or std::array.

Solution 4

Array is not a primitive type, and the arrays belong to different addresses in the C++ memory.

Solution 5

Nobody mentions memcmp? This is also a good choice.

/* memcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char buffer1[] = "DWgaOtP12df0";
  char buffer2[] = "DWGAOTP12DF0";

  int n;

  n=memcmp ( buffer1, buffer2, sizeof(buffer1) );

  if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
  else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
  else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);

  return 0;
}

Ref: http://www.cplusplus.com/reference/cstring/memcmp/

Share:
138,843
vladinkoc
Author by

vladinkoc

I want to learn c++.

Updated on December 01, 2020

Comments

  • vladinkoc
    vladinkoc over 3 years

    Can someone please explain to me why the output from the following code is saying that arrays are not equal?

    int main()
    {
    
        int iar1[] = {1,2,3,4,5};
        int iar2[] = {1,2,3,4,5};
    
        if (iar1 == iar2)
            cout << "Arrays are equal.";
        else
            cout << "Arrays are not equal.";
    
        return 0;   
    }