memcpy 和 strcpy 之间的区别

来源:互联网 发布:mac 梦幻西游不能更新 编辑:程序博客网 时间:2024/06/09 00:28

           1.  memcpy是用于内存复制,可以复制任意数据类型,而strcpy只针对字符串进行复制

           2. memcpy的申明是: void *memcpy(void *dest, const void *src, size_t n); 这里dest 和 src 都是使用的空指针,即在实际操作中可以使用不同的指针类型进行处理

               strcpy的申明是:char *strcpy(char *dest, const char *src); 即dest 和 src 都是字符串类型,而且src 是const char* ,即在函数体中,*src的数据是不可以改动的

           3. memcpy复制完的标准是复制n个数据, 而strcpy复制完成的标准是src字符串到了字符串的末尾,即'\0',而且dest字符串会加上'\0'结束符

           4. memcpy的汇编的简易实现方式(针对memcpy的优化有很多,其中在copy的时候,可以直接copy一个dword 而不是一个byte):

; =========================================================================;         void* memcpy(void* dst, const void* src, size_t count); =========================================================================my_memcpy:    push     ebp    mov    ebp, esp        push    ebx    push    ecx    xor    ebx, ebx    xor    ecx, ecx    mov    ecx, [ebp + 16]    mov    esi, [ebp + 12]    mov    edi, [ebp + 8]    mov    eax, edi.1:    cmp    ecx, 0    je    .2    mov    bl, byte[esi]    mov    byte[edi], bl    inc    esi    inc     edi    dec    ecx    jmp    .1    .2:    pop    ecx    pop    ebx    mov     esp, ebp    pop    ebp        ret          


 

            5 strcpy的c函数实现:

 /**  * copy the string of source to the destination string * * @note: (1) the destination string must have  enough space to load the string from source * * @param dest: the destination string to load the string * @param src: the source string that will be copied to the destination string * * @return: if success, return the pointer that point to the destination string *        if failure, return null */char* my_c_strcpy(char* dest, const char* src){    // check the string dest and src    assert(dest != MY_NULL && src != MY_NULL);    if (dest == src)    { // if the destionation position is equal to the source        return dest;        }        char* p = dest;        while (*src != 0)    {        *dest++ = *src++;        }        *dest = 0;    return p;}




原创粉丝点击