cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : C Library : cstring (string.h) : memcmp
 
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forum
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
C Library
cassert (assert.h)
cctype (ctype.h)
cerrno (errno.h)
cfloat (float.h)
climits (limits.h)
clocale (locale.h)
cmath (math.h)
csetjmp (setjmp.h)
csignal (signal.h)
cstdarg (stdarg.h)
cstddef (stddef.h)
cstdio (stdio.h)
cstdlib (stdlib.h)
cstring (string.h)
ctime (time.h)
cstring (string.h)
functions:
· memchr
· memcmp
· memcpy
· memmove
· memset
· strcat
· strchr
· strcmp
· strcoll
· strcpy
· strcspn
· strerror
· strlen
· strncat
· strncmp
· strncpy
· strpbrk
· strrchr
· strspn
· strstr
· strtok
· strxfrm
macros:
· NULL
types:
· size_t

-

memcmp function
int memcmp ( const void * ptr1, const void * ptr2, size_t num );
<cstring>

Compare two blocks of memory

Compares the first num bytes of the block of memory pointed by ptr1 to the first num bytes pointed by ptr2, returning zero if they all match or a value different from zero representing which is greater if they do not.

Parameters

ptr1
Pointer to block of memory.
ptr2
Pointer to block of memory.
num
Number of bytes to compare.

Return Value

Returns an integral value indicating the relationship between the content of the memory blocks:
A zero value indicates that the contents of both memory blocks are equal.
A value greater than zero indicates that the first byte that does not match in both memory blocks has a greater value in ptr1 than in ptr2 as if evaluated as unsigned char values; And a value less than zero indicates the opposite.

Example

/* memcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[256];
  char str2[256];
  int n;
  size_t len1, len2;
  printf ("Enter a sentence: "); gets(str1);
  printf ("Enter another sentence: "); gets(str2);
  len1=strlen(str1);
  len2=strlen(str2);
  n=memcmp ( str1, str2, len1>len2?len1:len2 );
  if (n>0) printf ("'%s' is greater than '%s'.\n",str1,str2);
  else if (n<0) printf ("'%s' is less than '%s'.\n",str1,str2);
  else printf ("'%s' is the same as '%s'.\n",str1,str2);
  return 0;
}

Output:


Enter a sentence: building
Enter another sentence: book
'building' is greater than 'book'.

building is greater than book because the first non-matching character in both words are 'u' and 'o' respectivelly, and 'u' (117) evaluates as greater than 'o' (111).

See also

memchr Locate character in block of memory (function)
memcpy Copy block of memory (function)
memset Fill block of memory (function)
strncmp Compare characters of two strings (function)
© The C++ Resources Network, 2000-2007 - All rights reserved
Spotted an error? - contact us