zoukankan      html  css  js  c++  java
  • 算法-memcopy与memmove的区别

    memcpy()和 memmove()都是C语言中的库函数,在头文件string.h中,作用是拷贝一定长度的内存的内容,原型如下

    void *memcpy(void *dst, const void *src, size_t count);

    描述:
            memcpy()函数从src内存中拷贝n个字节到dest内存区域,但是源和目的的内存区域不能重叠。
    返回值:
            memcpy()函数返回指向dest的指针。


    void *memmove(void *dst, const void *src, size_t count);

    描述:
           memmove() 函数从src内存中拷贝n个字节到dest内存区域,但是源和目的的内存可以重叠。
    返回值:
            memmove函数返回一个指向dest的指针。

    他们的作用是一样的,唯一的区别是,当内存发生局部重叠的时候,memmove保证拷贝的结果是正确的,memcpy不保证拷贝的结果的正确。

    下面来写 memmove()函数如何实现

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h>
    
    
    char * memcopy(char *source, char *destinatin, int count)
    {
        if (source == NULL || destinatin == NULL || count <= 0)
        {
            return 0;
        }
        char *sou_index = source;
        char *des_index = destinatin;
        if (des_index < sou_index &&  des_index + count > sou_index)
        {
            sou_index = source + count;
            des_index = destinatin + count;
            while (count--)
            {
                *sou_index-- = *des_index--;
            }
        }
        else {
            while (count--)
            {
                *sou_index++ = *des_index++;
            }
        }
        return source;
    }
    
    int main()
    {
        char a[] = "i am a teacher";
        char b[50] = {0};
        int len;
        len = sizeof(a);
        printf("%s", memcopy(b, a, len));
    }

    memcopy没有考虑内存重叠的情况,直接将上面的if语句里面的内容去掉就说memcopy的函数

  • 相关阅读:
    挑战程序设计竞赛 dp
    算法导论 动态规划
    算法导论第二章
    divide conquer
    时间戳
    bootstrap 针对超小屏幕和中等屏幕设备定义的不同的类
    jQuery中的Ajax
    怎么判断一个变量是Null还是undefined
    认识Ajax
    关于apache
  • 原文地址:https://www.cnblogs.com/cyyz-le/p/11215420.html
Copyright © 2011-2022 走看看