首页 > 编程知识 正文

memcmp(),memcmp的返回值

时间:2023-05-04 09:34:58 阅读:225288 作者:2562

memcmp函数: int memcmp (const void *s1, const void *s2, size_t n);

这个函数用来比较 s1 和 s2 所指的内存区间前 n 个字符。

第一个字符串大于第二个字符串,则返回大于0的数字;

第一个字符串等于第二个字符串,则返回0;

第一个字符串小于第二个字符串,则返回小于0的数字。

代码: #include<stdio.h>#include<assert.h>int my_memcmp(const void* buf1, const void* buf2, size_t count){ assert(buf1 != NULL && buf2 != NULL); const char* pf1 = (const char*)buf1; const char* pf2 = (const char*)buf2; int res = 0; while (count-- != 0) { res = *pf1 - *pf2; if (res != 0) break; pf1++; pf2++; } return res;}void main(){ char str1[20] = "hello"; char str2[20] = "helloworld"; int a = my_memcmp(str1, str2, 3); printf("%d", a);}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。