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;
}