user2138149
user2138149

Reputation: 16841

The use of strncmp and memcmp

Does

if(strncmp(buf, buf2, 7) == 0)

do the same thing as

if(memcmp(buf, buf2, 7) == 0)

buf and buf2 are char* arrays or similar.

I was going to append this to another question but then decided perhaps it was better to post it separately. Presumably the answer is either a trivial "yes" or if not then what is the difference?

(I found these functions from online documentation, but wasn't sure about strncmp because the documentation was slightly unclear.)

Upvotes: 2

Views: 2416

Answers (3)

pah
pah

Reputation: 4778

The main difference between strncmp() and memcmp() is that the first is sensible to (stops at) '\0' where the latest is not. If the first 7 bytes of memory from buf and buf2 do not contain a '\0' in it, then the behaviour is the same.

Consider the following example:

#include <stdio.h>
#include <string.h>

int main(void) {
    char buf[]  = "123\0 12";
    char buf2[] = "123\0 34";

    printf("strncmp(): %d\n", strncmp(buf, buf2, 7));
    printf("memcmp(): %d\n", memcmp(buf, buf2, 7));

    return 0;
}

It will output:

strncmp(): 0
memcmp(): -2

Because strncmp() will stop at buf[3], where it'll find a '\0', where memcmp() will continue until all 7 bytes are compared.

Upvotes: 2

John Bollinger
John Bollinger

Reputation: 180351

Like strcmp(), strncmp() is for comparing strings, therefore it stops comparing when it finds a string terminator in at least one argument. Any differences past that point have no effect on the result. strncmp() differs in that it will also stop comparing after the specified number of bytes if it does not encounter a terminator before then.

memcmp(), on the other hand, is for comparing blocks of random memory. It compares up to the specified number of bytes from each block until it finds a difference, regardless of the values of the bytes. That is, it does not stop at string terminators.

Upvotes: 8

Georg Schnabel
Georg Schnabel

Reputation: 631

In C and C++ the end of a string is indicated by a byte with value 0. The function memcmp does not care about the end of a strig but will in any case compare exactly the number of bytes specified.

In contrast to that, the function strncmp will stop at a byte with value 0 even though the passed number of bytes to compare is not yet reached.

Upvotes: 2

Related Questions