C memcmp() function
C memcmp() function - compare bytes in memory
Syntax:
int memcmp(const void *str1, const void *str2, size_t n)
The memcmp() function compares the first n bytes of str1 and str2.
Parameters:
Name | Description | Required /Optional |
---|---|---|
str1 | First buffer. | Required |
str2 | Second buffer. | Required |
n | Number of characters to compare. | Required |
Return value from memcmp()
- if Return value < 0 then it indicates str1 is less than str2.
- if Return value > 0 then it indicates str2 is less than str1.
- if Return value = 0 then it indicates str1 is equal to str2.
Example: memcmp() function
The following program uses memcmp to compare two strings.
#include <stdio.h>
#include <string.h>
int main( void )
{
char str1[] = "12345678901400345678";
char str2[] = "12345678901297650033";
int result;
printf("Original text:");
printf("\n%s",str1);
printf("\n%s",str2);
printf( "\n\nCompare first 10 characters of the said two strings");
result = memcmp( str1, str2, 10 );
if( result < 0 )
printf( "\nFirst is less than second.\n" );
else if( result == 0 )
printf( "\nFirst is equal to second.\n" );
else
printf( "\nFirst is greater than second.\n" );
printf( "\n\nCompare first 12 characters of the said two strings");
result = memcmp( str1, str2, 12 );
if( result < 0 )
printf( "\nFirst is less than second.\n");
else if( result == 0 )
printf( "\nFirst is equal to second.\n");
else
printf( "\nFirst is greater than second.\n");
char str3[] = "12345678901100345678";
char str4[] = "12345678901297650033";
printf("\n\nOriginal text:");
printf("\n%s",str3);
printf("\n%s",str4);
printf( "\n\nCompare first 19 characters of the said two strings");
result = memcmp( str3, str4, 19 );
if( result < 0 )
printf( "\nFirst is less than second.\n");
else if( result == 0 )
printf( "\nFirst is equal to second.\n");
else
printf( "\nFirst is greater than second.\n");
}
Output:
Original text: 12345678901400345678 12345678901297650033 Compare first 10 characters of the said two strings First is equal to second. Compare first 12 characters of the said two strings First is greater than second. Original text: 12345678901100345678 12345678901297650033 Compare first 19 characters of the said two strings First is less than second.
C Programming Code Editor:
Previous C Programming: C memchr()
Next C Programming: C memcpy()
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics