This documentation is copyright © 1998-2001 Sandro Sigala <sandro@sigala.it>.
All rights reserved.
Released under the GNU General Public License.
memcmp
Prototype
#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n);
Description
Compares the first n
bytes of the two memory areas s1
and s2
.
It returns an integer less than, equal to, or greater than zero
if s1
is found, respectively, to be less than, to match, or be
greater than s2
.
Implementation
#include <string.h>
int memcmp(const void *s1, const void *s2, size_t n)
{
const unsigned char *sp1, *sp2;
for (sp1 = s1, sp2 = s2; n > 0; ++sp1, ++sp2, --n)
if (*sp1 != *sp2)
return (*sp1 < *sp2) ? -1 : 1;
return 0;
}
Example
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* Check if two objects are equal (contain the same data).
*/
#define OBJEQ(obj1, obj2) \
(sizeof(obj1) == sizeof(obj2) && \
memcmp(&(obj1), &(obj2), sizeof(obj1)) == 0)
int main(void)
{
int a = 1, b = 1, c = 2;
int *bp = &b;
char d = 1;
printf("%d\n", OBJEQ(a, b)); /* Prints "1". */
printf("%d\n", OBJEQ(a, c)); /* Prints "0". */
printf("%d\n", OBJEQ(a, *bp)); /* Prints "1". */
printf("%d\n", OBJEQ(a, d)); /* Prints "0". */
return EXIT_SUCCESS;
}
References
ISO C 9899:1990 7.11.4.1