+ 1

Bool function problem

#include <iostream> using namespace std; bool eq ( char s[]) { int size = sizeof(s); for ( int i = 0; i < size/2 ; i++) { if ( s[i] != s[size/2 +i] ) return false; } return true; } int main() { char s[] = "abcabc"; cout<<eq(s); return 0; } Someone can tell me why always it's return 0 ? Thanks!

20th Feb 2018, 12:40 PM
Avihu
Avihu - avatar
1 Odpowiedź
+ 3
Here is the corrected version, just changed sizeof to strlen. You see, sizeof(s) may not exactly return the correct size of the string. #include <iostream> #include <cstring> using namespace std; bool eq ( char s[]) { int size = strlen(s); // Use strlen instead of sizeof. for ( int i = 0; i < (size/2) ; i++) { if( s[i] != s[(size/2)+i] ) return false; } return true; } int main() { char s[] = "abcabc"; cout<<eq(s); return 0; }
20th Feb 2018, 1:45 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar