+ 2

Why is the output 0 not 1 in the following programme? Please explain.

char a[]={"hello"}; char b[6]={"hello"}; cout<<(a==b);

28th Apr 2017, 12:39 AM
Karan Kumar Bedia
Karan Kumar Bedia - avatar
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.
28th Apr 2017, 1:51 AM
Nelson Urbina
Nelson Urbina - avatar
+ 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'
28th Apr 2017, 2:50 AM
Nelson Urbina
Nelson Urbina - avatar
+ 1
Try: cout << a << endl; cout << b << endl; to see what happen.
28th Apr 2017, 12:58 AM
Yusuf Malikul Mulki
Yusuf Malikul Mulki - avatar