Q19 Write your own function of memcmp().

memcmp() function is used to perform byte by byte comparison. Given below user defined memecmp() function.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int own_memcmp(const void *buf1, const void *buf2, int cnt)
{

if(!cnt)
{

return 0;

}
while(- -cnt && (*(char *)buf1 == *(char *)buf2))
{

buf1 = (char *)buf1 + 1;
buf2 = (char *)buf2 + 1;

}
return ( *((unsigned char *)buf1) – *((unsigned char *)buf2));

}

int main()
{

char *ptr = NULL;
char *ptr1 = NULL;
int diff = 0;

ptr = (char*)malloc(25);
ptr1 = (char*)malloc(25);

printf(“Enter value of ptr nad ptr1\n”);
gets(ptr);
gets(ptr1);

diff = own_memcmp(ptr, ptr1, 10);
printf(“Diff = %d\n”,diff);

free(ptr);
free(ptr1);
return 0;

}

Output:

$ ./a.exe
Enter value of ptr nad ptr1
welcome to gyantoday
welcome to gyantoday
Diff = 0

$ ./a.exe
Enter value of ptr nad ptr1
ABCDEFGHIJKLMN
ABDGFSAJFLFHSK
Diff = -1

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.