memcmp Function

Compare the contents of two buffers.

Include

<string.h>

Prototype

int memcmp(const void *s1, const void *s2, size_t n);

Arguments

s1
first buffer
s2
second buffer
n
number of characters to compare

Return Value

Returns a positive number if s1 is greater than s2, zero if s1 is equal to s2 or a negative number if s1 is less than s2.

Remarks

This function compares the first n characters in s1 to the first n characters in s2 and returns a value indicating whether the buffers are less than, equal to or greater than each other.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

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

int main(void)
{
  char buf1[50] = "Where is the time?";
  char buf2[50] = "Where did they go?";
  char buf3[50] = "Why?";
  int res;

  printf("buf1 : %s\n", buf1);
  printf("buf2 : %s\n", buf2);
  printf("buf3 : %s\n\n", buf3);

  res = memcmp(buf1, buf2, 6);
  if (res < 0)
    printf("buf1 comes before buf2\n");
  else if (res == 0)
    printf("6 characters of buf1 and buf2 "
           "are equal\n");
  else
    printf("buf2 comes before buf1\n");
  printf("\n");

  res = memcmp(buf1, buf2, 20);
  if (res < 0)
    printf("buf1 comes before buf2\n");
  else if (res == 0)
    printf("20 characters of buf1 and buf2 "
           "are equal\n");
  else
    printf("buf2 comes before buf1\n");
  printf("\n");

  res = memcmp(buf1, buf3, 20);
  if (res < 0)
    printf("buf1 comes before buf3\n");
  else if (res == 0)
    printf("20 characters of buf1 and buf3 "
           "are equal\n");
  else
    printf("buf3 comes before buf1\n");
}

Example Output

buf1 : Where is the time?
buf2 : Where did they go?
buf3 : Why?

6 characters of buf1 and buf2 are equal

buf2 comes before buf1

buf1 comes before buf3