memcmp c: The function int memcmp(const void *ptr1, const void *ptr2, size_t n); compares first n bytes starting from memory location pointed by ptr1 with first n bytes starting from memory location pointed by ptr2.
Function prototype of memcmp
int memcmp(const void *ptr1, const void *ptr2, size_t n);
- ptr1 : A pointer to the block of memory.
- ptr2 : A pointer to the block of memory.
- n : This is the number of bytes to compare.
Return value of memcmp
Return Value | Description |
---|---|
Positive (>0) | ptr1 is greater than ptr2 |
Zero (==0) | ptr1 is equal to ptr2 |
Negative (<0) | ptr1 is less than ptr2 |
C program using memcmp function
C memcmp: The following program shows the use of memcmp function to compare two strings.
#include <stdio.h> #include <string.h> #include <conio.h> int main() { char firstString[100], secondString[100]; int length, response; printf("Enter length of strings\n"); scanf("%d", &length); printf("Enter first string of length %d\n", length); scanf("%s", &firstString); printf("Enter second string of length %d\n", length); scanf("%s", &secondString); response = memcmp(firstString, secondString, length); if(response > 0) { printf("second String is less than first String"); } else if(response < 0) { printf("first String is less than second String"); } else { printf("first String is equal to second String"); } getch(); return(0); }
Output
Enter length of strings 7 Enter first string of length 7 ASDFGHJ Enter second string of length 7 QWERTYU first String is less than second String