memcpy()与strcpy()的完全实现

来源:互联网 发布:雀神作弊软件 编辑:程序博客网 时间:2024/04/30 14:10

memcpy()用来拷贝src所指的内存内容前n个字节到dest所指的内存地址上。与strcpy()不同的是,memcpy()会完整的复制n个字节,不会因为遇到字符串结束'\0'而结束
mem是一段記憶體,他的長度,必須你自己記住
str也是一段記憶體,不過它的長度,你不用記,隨時都可以計算出來
所以memcpy需要第三個參數,而strcpy不需要
==============================
memcpy()的实现
难点:1.指针类型的变换
         2.要防止内存拷贝时的相互覆盖
#include <iostream>
#include "assert.h"
using namespace std;


void* memcpy(void* dest,const void* source,int lengh)
{
    assert((dest!=NULL)&&(source!=NULL));    //断言
  if(dest < source)
    {
        char* cdest = (char*)dest;
        const char* csource = (char*)source;
        for(int i=0;i<lengh;i++)
            *cdest++ = *csource++;
  return cdest;
    }
    else
    {
        char* cdest = (char*)(dest)+lengh-1;
        char* csource = (char*)(source)+lengh-1;
        for(int i=0;i<lengh;i++)
            *cdest-- = *csource--;
  return cdest;
    }
   
}

int main()
{
    char* a = "he\0llo";
    char b[10];
 memcpy(b,a,10);
 for(int k=0;k<6;k++)
  cout << b[k] <<endl;
    return 0;
}
输出:
h
e

l
l
o
=================================
strcpy()的实现。
char* strcpy(char* dest,const char* source)
{
     assert(dest!=NULL&&source!=NULL);
     while((*dest++ = *source++) != '\0')
                            ;
     return dest;
}
==================================
可用一下函数来观察memcpy()与strcpy()的区别
#include <string.h>
#include <stdio.h>

int main()
{
    char a[30] = "string (a)";
    char b[30] = "hi\0zengxiaolong";
    int i;

    strcpy(a, b);             //a[30] = "hi\0ing (a)"
    printf("strcpy():");
    for(i = 0; i < 30; i++)
        printf("%c", a[i]);   //hiing (a)


    memcpy(a, b, 30);         //a[30] = "hi\0zengxiaolong"
    printf("\nmemcpy():");
    for(i = 0; i < 30; i++)
        printf("%c", a[i]);   //hizengxiaolong
    printf("\n i = %d\n", i); //30

}