memcpy 和 strcpy 之间的区别

           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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值