C language: Simulate and implement memcmp. Compare the differences between memcmp, strcmp, and strncmp.

Source: Internet
Author: User

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 ;}

 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.