memcmp()用于数组比较

博客介绍了memcmp()函数在C++中的使用,除了比较字符串外,还能用于比较两个int数组的元素是否相同。当所有元素都相同时,memcmp()返回0。文中包含示例代码及运行结果的讨论。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

memcmp()用于数组比较

C++ Reference:

链接: cstring之memcmp.
(http://www.cplusplus.com/reference/cstring/memcmp/)
示例给出了一种类似strcmp的用法,可以用它来比较字符串……

Example
/* memcmp example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char buffer1[] = "DWgaOtP12df0";
  char buffer2[] = "DWGAOTP12DF0";

  int n;

  n=memcmp ( buffer1, buffer2, sizeof(buffer1) );

  if (n>0) printf ("'%s' is greater than '%s'.\n",buffer1,buffer2);
  else if (n<0) printf ("'%s' is less than '%s'.\n",buffer1,buffer2);
  else printf ("'%s' is the same as '%s'.\n",buffer1,buffer2);

  return 0;
}
结果

‘DWgaOtP12df0’ is greater than ‘DWGAOTP12DF0’.
DWgAOtp12Df0 is greater than DWGAOTP12DF0 because the first non-matching character in both words are ‘g’ and ‘G’ respectively, and ‘g’ (103) evaluates as greater than ‘G’ (71).
在这里插入图片描述

重点来了,除此以外,memcmp还可以——

可以比较两个int数组里面的元素是否相同

memcmp(a,b,sizeof(a));  //int a[],b[]
都相同则返回值为0。

简单写一下测测:

示例代码

#include <stdio.h>
#include <string.h>

int main() {
    int a[10]={1,2,3,4};
    int A[10]={1,2,3,4};
    int b[10]={5,6,7,8};
    printf("%d\n",memcmp(a,b,sizeof(a)));
    printf("%d\n",memcmp(a,A,sizeof(a)));
    printf("%d\n",memcmp(b,a,sizeof(a)));

    return 0;
}

运行结果

在这里插入图片描述

tbc.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值