Difference between memcmp() and strncmp() functions

P

Preets

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

Richard Bos

Preets said:
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
 
P

pete

Richard said:
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.
 
P

pete

pete said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top