• strcpy strlen memcpy等的函数实现


    #include <assert.h>
    #include <string.h>
    #include <stdlib.h>
    #include <stdio.h>

    char *StrCpy(char *dest, const char *src)
    {
    assert((dest != NULL) && (src != NULL));
    char *str = dest;
    while ((*dest ++ = *src ++) != '');
    return str;
    }

    int Strlen(const char *str)
    {
    assert((str != NULL));
    int len = 0;
    while (*str ++)
    {
    len++;
    }
    return len;
    }

    int StrCmp(const char *str1, const char *str2)
    {
    assert((str1 != NULL) && (str2 != NULL));
    int rt = 0;
    while ( !(rt = *(unsigned char *)str1 - *(unsigned char*)str2 ) && *str2)
    {
    str1 ++;
    str2 ++;
    }
    if (rt > 0)
    {
    rt = 1;
    }
    else if (rt < 0)
    {
    rt = -1;
    }
    return rt;
    }

    //为了解决内存重叠的现象
    void *MemCpy(void *dst, const void *src, size_t count)
    {
    char *pdst = static_cast<char *>(dst);
    const char *psrc = static_cast<const char *>(src);

    if (pdst > psrc && pdst < psrc + count)
    {
    for (int i = count - 1; i >= 0; i--)
    {
    pdst[i] = psrc[i];
    }
    }
    else
    {
    for (int i = 0; i < count; i++)
    {
    pdst[i] = psrc[i];
    }
    }
    return dst;
    }

    // memcpy 实现源码
    void * __cdecl memcpy (
    void * dst,
    const void * src,
    size_t count
    )
    {
    void * ret = dst;

    while (count--) {
    *(char *)dst = *(char *)src;
    dst = (char *)dst + 1;
    src = (char *)src + 1;
    }

    return(ret);
    }

    int main()
    {
    char str2[100] = "abcd";
    char *str1 = (char *)malloc(100);
    str1= str2 + 2;
    //考虑了内存重叠
    MemCpy(str1, str2, 5);
    printf("调用MemCpy后str1的内容: %s ", str1);

  • 相关阅读:
    用Python完成Excel的常用操作
    用Python实现excel 14个常用操作
    ubuntu and centos各种上网代理设置
    vim 熟练度练习
    Ansible-playbook 使用方式 看一篇就够了
    python 使用ldap3 查询跨域的用户信息
    python pyinstaller 的使用
    vs code新建python虚拟环境
    vs code 远程开发环境设置
    上下文管理器(Context Manager)
  • 原文地址:https://www.cnblogs.com/reality-soul/p/6178333.html
Copyright © 2020-2023  润新知