C语言函数memcpy(),memmove(),memcmp()用法详解

来源:互联网 发布:淘宝指数查询网址 编辑:程序博客网 时间:2024/05/18 06:00
I.memcpy()和函数头文件:#include <string.h>函数原型:void *memcpy(void *dest, const void *src, size_t n);功能:拷贝src所指的内存内容的前n个字节复制(拷贝)到dest所值的内存地址上。参数:    dest:目的内存首地址    src:源内存首地址,注意:dest和src所指的内存空间不可重叠    n:需要拷贝的字节数返回值:dest的首地址示例代码I:(拷贝字符串)#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAX 15int main(){    char src[]="hello world.";    int len = sizeof(src);    char dst[MAX];    memcpy(dst,src,len);    printf("src = %s\n",src);    printf("dst = %s\n",dst);    system("pause");    return 0;}该代码得功能是将src所指向的内存中的内容hello world.复制到dst所指向的内存区域中,大小为len;其实这个memcpy()函数的实现很简单, 下面自己来实现这个memcpy()函数的功能:#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAX 15void func(char *dst,const char *src,int len){    while (--len >= 0)    {        *dst++ = *src++;    }}int main(){    char src[]="hello world.";    int len = sizeof(src);    char dst[MAX];    func(dst,src,len);    printf("src = %s\n",src);    printf("dst = %s\n",dst);    system("pause");    return 0;}示例代码II (拷贝整型数组)#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAX 15void func(char *dst,const char *src,int len){    while (--len >= 0)    {        *dst++ = *src++;    }}int main(){    char buf[] = {1,2,3,4,5};    char arr[MAX]={0};    int len = sizeof(buf)/sizeof(buf[0]); //计算数组元素个数    int i = 0;    memcpy(arr,buf,sizeof(buf));    for(i=0;i<len;i++)    {        printf("%2d",arr[i]);    }    putchar('\n');    system("pause");    return 0;}打印结果为:1   2   3   4   5II.memmove()函数memmove()函数和memcpy()函数的功能相差不多,但是memcpy()函数有一个限制,就是目的地址(dst)和源地址(src)不能重叠;而memmvoe()函数则没有这个限制,不过memmove()函数也有它自己的缺点,就是执行的效率要比memcpy()函数低一些。III. memcmp()函数#include <string.h>int memcmp(const void *s1, const void *s2, size_t n);功能:比较s1和s2所指向内存区域的前n个字节参数:    s1:内存首地址1    s2:内存首地址2    n:需比较的前n个字节返回值:    相等:=0    大于:>0    小于:<0示例代码I.(比较src和dst字符串)#include <stdio.h>#include <string.h>#include <stdlib.h>#define MAX 15void func(char *dst,const char *src,int len){    while (--len >= 0)    {        *dst++ = *src++;    }}int main(){    char *src = "hello world.";    char *dst = "welcome to you.";    int flag  = memcmp(dst,src,5);    if (0 == flag)    {        printf("be equal\n");    }    else if (-1 == flag)    {        printf("src < dst");    }    else    {        printf("src > dst");    }    system("pause");    return 0;}打印结果:    src > dst
1 0
原创粉丝点击