c++ - Why does my version of strcmp not work? -
i have own version of strcmp looks this
int strcmp(char str1[], char str2[]) { int = 0; while ((str1[i] == str2[i]) && (str1[i] != '\0')) { i++; } if (str1[i] > str2[i]) return 1; if (str1[i] < str2[i]) return -1; return 0; }
and test case
char a[20]; char b[20]; b[0] = 'f'; a[0] = 'f'; cout << strcmp(b, a) << endl;
however, output of 1, meaning not equal each other. if swap , b's position in function call -1. not sure why unable 0 return in comparison when char's both 'f'. feel basic , don't know why comparison off
str1[i] > str2[i]
you've left arrays uninitialized , changed first elements of each. means instead of comparing strings "f" , "f" against 1 another, you're comparing 2 blocks of 20 bytes each against 1 another, except each of blocks starts "f". (actually, since arrays aren't null-terminated, you're comparing 2 random regions of memory together!)
try changing test cases use strcpy
initialize arrays. should fix issue.
Comments
Post a Comment