+ 2
Why is the output 0 not 1 in the following programme? Please explain.
char a[]={"hello"}; char b[6]={"hello"}; cout<<(a==b);
3 Respostas
+ 4
Well, that's because you have two char arrays, which technically speaking are not exactly strings. When you use the == operator on two array identifiers, you are actually comparing their address in memory (which in most cases are different unless one is a reference of the other).
An string is an object from the string class, which has an implementation of the == operator that calls the compare() member function of the class. Probably, the compare function "compares each pairs of character of the strings one by one and should return true (1) when comparing two strings which contains the same characters.
+ 4
@Emore Not really. In C, when you use char arrays to store strings, the string end is indicated by the '\0' char which is added at the end of the array automatically by the compiler. That's why the array length has to be equal to the string length plus one. So, both of the above arrays contain 6 characters in total, being the last character equal to '\0'
+ 1
Try:
cout << a << endl;
cout << b << endl;
to see what happen.