How to implement the memcmp function in C

1 Answer

0 votes
#include <stdio.h>

int memcmp(const void* s1, const void* s2, size_t n) {
	// compare the first n bytes of str1 and str2
	const unsigned char* str1 = (const unsigned char*)s1;
	const unsigned char* str2 = (const unsigned char*)s2;

	for (; 0 < n; str1++, str2++, n--)
		if (*str1 != *str2)
			return *str1 < *str2 ? -1 : +1;
	return 0;
}

int main()
{
	char str1[32] = "c programming";
	char str2[32] = "c programming";
	
	int result = memcmp(str1, str2, 5);

	if (result > 0) {
		printf("str1 > str2");
	}
	else if (result < 0) {
		printf("str2 > str1");
	}
	else {
		printf("str1 == str2");
	}

	return 0;
}




/*
run:
    
str1 == str2
    
*/

 



answered Dec 16, 2022 by avibootz

Related questions

1 answer 92 views
92 views asked Jun 10, 2025 by avibootz
1 answer 142 views
1 answer 143 views
1 answer 111 views
111 views asked Aug 2, 2024 by avibootz
2 answers 234 views
234 views asked Jan 7, 2024 by avibootz
1 answer 133 views
...