Understanding Array Equality Comparison in C
When comparing arrays using the == operator, programmers often encounter unexpected results. To delve into this issue, let's analyze the code snippet below:
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."; }
Despite containing identical elements, the code outputs "Arrays are not equal." To understand this behavior, we must examine how C handles array comparisons.
When comparing arrays using ==, the expression reduces to comparing the pointers to the first elements of each array. However, in this case, iar1 and iar2 represent two distinct arrays stored at different memory addresses. Thus, they evaluate to unequal pointers, resulting in the "not equal" output.
To perform an element-wise comparison, alternative approaches can be employed. One method involves using a loop to compare each element individually. Alternatively, for C 11 and later, std::array provides a more structured approach for array handling. In the revised code below, std::array is utilized to represent the arrays, and the == operator performs element-wise comparison, yielding the expected result:
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 }
The above is the detailed content of Why Do C Arrays Compare as Unequal Using the == Operator?. For more information, please follow other related articles on the PHP Chinese website!