Comparing Two Arrays in C: By Contents and By Address

Comparing Two Arrays in C

This C program compares two distinct arrays and if the arrays are same then content results in FALSE. The behavior of comparison is explained when we note that the comparison is a comparison of addresses, not contents.

Comparing Arrays by Addresses

#include < stdio.h >

  int main(void) {
    int a[2] = {1, 2}; 
    int b[2] = {2, 3};
    int i;

    for (i = 0; i < 2; i++) {
      a[i] = b[i];
    }

    // The comparison of two distinct arrays with the same content
    // results in FALSE. So below we print "They are not equal"
    if (a == b) {
      printf("They are equal\n");
    } else {
      printf("They are not equal\n");
    }

    // The following comparison results in TRUE. 
    if (a == a) {
      printf("Of course a is equal to a\n");
    } else {
      printf("No, a is not equal to a\n");
    }

        //  Print the elements of array a
    for (i = 0; i < 2; i++) {
        printf("a[%d] = %d\n", i, a[i]);
    }

    //  Print the elements of array b
    for (i = 0; i < 2; i++) {
        printf("a[%d] = %d\n", i, b[i]);
    }
  }

Comparing Arrays by Addresses

In this updated code, we added a loop to compare each element of arrays a and b. If any pair of corresponding elements is not equal, the equal variable is set to 0, indicating that the arrays are not equal. The result is then printed based on the value of the equal variable.

#include <stdio.h>

int main(void) {
    int a[2] = {1, 2};
    int b[2] = {2, 3};
    int i;

    // Copy elements from array b to array a 
    for (i = 0; i < 2; i++) {
        a[i] = b[i];
    }

    // Compare the contents of arrays a and b 
    int equal = 1; // Assume arrays are equal

    for (i = 0; i < 2; i++) {
        if (a[i] != b[i]) {
            equal = 0; // Arrays are not equal
            break;
        }
    }

    // Print the result based on the equality check 
    if (equal) {
        printf("They are equal\n");
    } else {
        printf("They are not equal\n");
    }

    //  Print the elements of array a
    for (i = 0; i < 2; i++) {
        printf("a[%d] = %d\n", i, a[i]);
    }

    //  Print the elements of array b
    for (i = 0; i < 2; i++) {
        printf("a[%d] = %d\n", i, b[i]);
    }

    return 0;
}
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post