Comparing two distinct C arrays of identical contents: what does this program print?
#include
int main()
{
char str1[] = "Hello";
char str2[] = "Hello";
if (str1 == str2)
printf("Equal
");
else
printf("Unequal
");
return 0;
}
-
AEqual
-
BUnequal
-
CError
-
DNone of above
-
EEqual on some compilers, Unequal on others
Answer
Correct Answer: Unequal
Explanation
Introduction / Context:In C, arrays are not directly comparable by value with ==. When used in expressions, array names decay to pointers to their first elements. This program compares the addresses of two separate arrays, not their string contents.
Given Data / Assumptions:
- Two separate arrays: str1 and str2, each initialized with "Hello".
- The expression str1 == str2 compares the addresses of the first elements of each array.
- They are distinct objects in memory.
Concept / Approach:Since str1 and str2 denote different storage, their addresses are different, so pointer equality is false. Value comparison of strings requires strcmp (or memcmp for raw bytes) rather than ==. Therefore the else branch executes and prints "Unequal".
Step-by-Step Solution:str1 and str2 each hold "Hello" and terminate with '\0'.When compared with ==, they decay to pointers (char*).The pointers do not reference the same memory location, so comparison is false.Program prints "Unequal".
Verification / Alternative check:Using if (strcmp(str1, str2) == 0) would print "Equal". Or assign one pointer to reference the other’s buffer (char *p = str1; char *q = str1;), then p == q would be true.
Why Other Options Are Wrong:“Equal” mistakes value equality for pointer equality. “Error” is incorrect; code compiles. The “depends on compiler” option is wrong; the objects are distinct by definition.
Common Pitfalls:Confusing array names with pointers; relying on == for string content comparison instead of strcmp.
Final Answer:Unequal