Hello friends today i have created a program that is working fine . but when string becomes equal it does not work .
/* String.h header series
Comparison function
memcmp = return 0 if string equal else return less or greater than value by comparing pointer first and pointer second
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
/*memcmp operation*/
int i;
char str[20];
char str2[20];
printf("Enter first string: ");
fgets(str,20,stdin);
printf("Enter second string: ");
fgets(str2,20,stdin);
fflush(stdin);
i = memcmp(str,str2,20);
if(i>0){
printf("%s greater than %s\n",str,str2);
}
else if(i<0) {
printf("%s greater than %s\n",str2,str);
}
else { printf("Both are eqaul\n"); }
return 0;
}
output:
[root@apache ~]# ./mem
Enter first string: hello
Enter second string: hello
hello greater than hello
memcmp is not working if string equal and it does not return 0 on equality of string , is this a bug ?
strcmp, strncmp and other similar functions are used to do string compares. A C string is terminated with a nul (ascii 0) character. This allows strcmp to determine the string's length and stop comparing. memcmp compares objects in memory. It does not check the length because it is meant to compare memory objects which often have ascii 0 characters.
You provide the length to memcmp. 20 is not the length of the word hello
If you don�t initialize str and str2 with the same values, these areas will contain random values, so the memcmp comparison will not match, even if they both have some values in common (both begin with 'h','e','l','l','o', but you don�t know what each have after the 5 first characters, cause it is uninitialized memory).
Yes Rink, but be aware that for string comparisons, strcmp - and its safe version, strncmp - are better suited, since they are specifically designed for working with strings.