C programming memcmp string.h

In C programming the <string.h> memcmp function compares a specific number of memory blocks for their equality in their content.The declaration of the function.

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

s1 -The first string.

s2 -The second string.

n -The number of characters

Return type
int -Returns 0 if ‘n’ memory blocks matches in s1 and s2;returns value greater than 0 if s1 has greater values in ‘n’ memory blocks; returns value less than 0 if s1 has lesser values in ‘n’ memory blocks.

Note this function is un-effective for comparison between two structure objects.

Code example

char s1[] = “abcdefghi jklmn”, s2[] = “abcdefghijklmn”;

int ret;

ret = memcmp(s1, s2, 9);

printf(“ret=%d”, ret);

long l1[] = { 1 ,2 ,34 }, l2[] = { 2 , 2 , 34 } , l3[] ={0 , 2 , 34};

ret=memcmp(l2 , l1, 3);

printf(“\nret=%d”, ret);

ret = memcmp(l3 , l1, 3);

printf(“\nret=%d”, ret);



The first 9 characters of s1 and s2 are equal so 0 is returned.The first value of ‘l2’ is greater than the first value of ‘l1’ so 1 is returned.And for the third call the first value of ‘l3’ is smaller than first value of ‘l1’ so -1 is returned.

Related links

->C strcmp string.h

->C strncmp string.h

->C strcoll string.h