Hi Guys, First post here, so be gentle :-)
I was going looking for an implementation of memcmp(), I found this code snippet, but it is clearly marked that there is 1 logical error with the code snippet. Could you help me find the logical error.
Basically, I tested this code against the string.h library implementation of memcmp() with different inputs, but the expected output is always the same as the library version of the function.
Here is the code snippet:
#include <stdio.h>
#include <string.h>
int memcmp_test(const char *cs, const char *ct, size_t n)
{
size_t i;
for (i = 0; i < n; i++, cs++, ct++)
{
if (*cs < *ct)
{
return -1;
}
else if (*cs > *ct)
{
return 1;
}
else
{
return 0;
}
}
}
int main()
{
int ret_val = 20; //initialize with non-zero value
char *string1 = "china";
char *string2 = "korea";
ret_val = memcmp_test(string1,string2,5);
printf ("ret_val is = %d",ret_val);
getchar();
return 0;
}
I ran the program with the two example strings and the program would return just after the comparison of the first characters of the two strings. ret_val is -1 in the above case.
The definition of memcmp() which the above code snippet should conform to is:
The definition of the ‘C’ Library function memcmp is
int memcmp(const char *cs, const char *ct, size_t n)
Compare the first n characters of cs with the first n characters of ct.
Return < 0 if cs < ct.
Return > 0 if cs > ct.
Return 0 if cs == ct.
There is definitely on LOGICAL error, could you help me find it.