C language: Simulate and implement memcmp. Compare the differences between memcmp, strcmp, and strncmp.
Memcmp: this function is similar to strcmp and can be used to compare strings. If it is the same, a value of 0 is returned. If the former is greater than the latter, an integer value greater than 0 is returned; otherwise, an integer value less than 0 is returned. The difference is: strcmp can only compare strings, memcmp is a memory comparison function, in principle, it is a memory comparison, but in fact not all can be compared in actual implementation, such as float, but we can at least compare string and int type. For strcmp, strncmp comparison: str1 and str2 are the two strings to be compared, and n is the number of characters to be compared, but the strcmp () function cannot. strcmp () you can compare all strings (because it finds the string ending sign '\ 0 '). The Code is as follows:
# Define _ CRT_SECURE_NO_WARNINGS 1 # include <stdio. h> # include <stdlib. h> # include <assert. h> int my_memcmp (const void * p1, const void * p2, size_t count) {assert (p1); assert (p2); char * dest = (char *) p1; char * src = (char *) p2; while (count & * dest = * src) {count --; dest ++; src ++ ;} if (count = 0) return 0; else return * dest-* src;} int main () {/* int arr1 [] = {1, 3, 20, 5}; // compare integer int arr2 [] = {1, 3, 10, 7}; */char arr1 [] = "hello "; // compare the string char arr2 [] = "hello world"; int len = sizeof (arr1)/sizeof (arr1 [0]); int ret = my_memcmp (arr1, arr2, 12); printf ("% d", ret); system ("pause"); return 0 ;}