+ 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!
1 Resposta
+ 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;
}