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

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -