Hi,
Can anybody please tell me the difference between memcmp() and
strncmp() functions ?
> Can anybody please tell me the difference between memcmp() and
> strncmp() functions ?
strncmp() stops at a null byte as well as at n bytes.
E.g., suppose you have the following:
at address a, you have the string "abcde", followed (of course) by a
terminating null character, followed by four chars of garbage;
at address b, you have the string "abcde", followed by a null char,
followed by four chars of different garbage than that at a;
then strncmp(a,b, 10) would return 0, since the _strings_ at those
addresses are equal, up to the first terminating null;
but memcmp(a,b, 10) would return a non-zero value depending on whether
the garbage at a is greater or smaller than that at b.
Richard
Also, strncmp stops at the first difference.
memcmp is allowed to compare the entire n number of bytes
regardless of whether or not the first bytes compare as different.
If n is equal to sizeof(int)
and if sizeof(int) is greater than two, then:
memcmp("a", "b", n) is undefined though
strncmp("a", "b", n) is defined.
--
pete
That's not right.
strncmp("a", "b", 3) is defined,
for the reason that Richard Bos gave,
which is that strncmp stops at a null byte as well as at n bytes.
--
pete