By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,505 Members | 1,168 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,505 IT Pros & Developers. It's quick & easy.

Difference between memcmp() and strncmp() functions

P: n/a


Hi,
Can anybody please tell me the difference between memcmp() and
strncmp() functions ?

May 1 '06 #1
Share this Question
Share on Google+
4 Replies


P: n/a
"Preets" <pr***********@gmail.com> wrote:
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
May 1 '06 #2

P: n/a

Thank you Richard...your example cleared my doubt :-)

May 1 '06 #3

P: n/a
Richard Bos wrote:

"Preets" <pr***********@gmail.com> wrote:
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:


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
May 1 '06 #4

P: n/a
pete wrote:

Richard Bos wrote:

"Preets" <pr***********@gmail.com> wrote:
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:


Also, strncmp stops at the first difference.


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
May 1 '06 #5

This discussion thread is closed

Replies have been disabled for this discussion.