So I have this (not the full code)
char list[1000][10];
strcpy(list[0],"ab");
printf("%d\n",strcmp(list[0],"ab"));
and the strcmp is returning 0. Can somebody explain why it's doing so?
Thanks in advance.
So I have this (not the full code)
char list[1000][10];
strcpy(list[0],"ab");
printf("%d\n",strcmp(list[0],"ab"));
and the strcmp is returning 0. Can somebody explain why it's doing so?
Thanks in advance.
The strcmp
method will return 0 if list[0]
contains "ab" in this case.
It returns:
Returns an integral value indicating the relationship between the strings:
A zero value indicates that both strings are equal.
A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.
strmp
returns 0 when the strings match. Unless I am missing something, it's behaving as expected.
strcmp()
does an ordinal comparison of the strings, not an equality test. The return value of 0 means the strings are equal!
If you want to test for equality use this pattern:
if (strcmp(s, "ab") == 0) {
// strings are equal
}
Because strcpy()
is a function that copies the "right" string to the "left" string.
So, after strcpy(list[0],"ab");
, the content of list[0]
is "ab".
Then, they are equal strings, and strcmp returns 0, which means "equal".
Your String is matched that is why it is returning 0 do like this...
char list[1000][10];
strcpy(list[0],"ab");
if(strcmp(list[0],"ab")==0)
printf("Matched\n",);
As mentioned by Daniel, the returnd value is 0.
Taken from cplusplus.com
Returns an integral value indicating the relationship between the strings: A zero value indicates that the characters compared in both strings form the same string. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.
You should also work with strncmp
rather than with strcmp
.