关闭

memcpy memmove strcat strcopy strlen实现

824人阅读 评论(0) 收藏 举报

1. 如何实现如下copy函数,高手指教:
void memcopy(void *s,void *t, int length)
/* 要求实现内存拷贝length长度内容,源为*t,目的为*s    */
希望大家讨论,看如何正确的实现!

考虑到源地址和目的地址交叉的情况:
#include <stdio.h>
#include <memory.h>
#include <string.h>

//考虑到源地址和目的地址交叉的情况
void * my_memcpy( void *dest, const void *src, size_t count )
{
 unsigned char *psrc = (unsigned char*) src;
 unsigned char *pdst = (unsigned char*) dest;

 if (!pdst || !psrc || count <= 0)
  return dest;
 
 if (psrc < pdst) // 目的地址比源地址高,从后开始拷贝
 {
  psrc += count-1;
  pdst += count-1;
  
  do {
   *pdst-- = *psrc--;
  } while(--count);
 }
 else if (psrc > pdst) // 目的地址比源地址低,从前开始拷贝
 {
  do {
   *pdst++ = *psrc++;
  } while (--count);
 }
 
 return dest;
}

void * __cdecl memmove (
        void * dst,
        const void * src,
        size_t count
        )
{
        void * ret = dst;

        if (dst <= src || (char *)dst >= ((char *)src + count)) {
                /*
                 * Non-Overlapping Buffers
                 * copy from lower addresses to higher addresses
                 */
                while (count--) {
                        *(char *)dst = *(char *)src;
                        dst = (char *)dst + 1;
                        src = (char *)src + 1;
                }
        }
        else {
                /*
                 * Overlapping Buffers
                 * copy from higher addresses to lower addresses
                 */
                dst = (char *)dst + count - 1;
                src = (char *)src + count - 1;

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

2. 编写一个标准strcpy函数

char * strcpy( char *strDest, const char *strSrc )
{ 
  char *address = strDest;
 assert( (strDest != NULL) && (strSrc != NULL) );
 
 while( *strDest++ = * strSrc++ );
 

 return address;
}

3. strlen函数

size_t strlen( const char *str ) //输入参数const
{
 
char *old = str;
 assert( str != NULL ); //断言字符串地址非0
 
 while( *str++ );
  
 
return str-old-1;
}

4.strcat实现
char *my_strcat(char *dest,char *src)
{
 if ( NULL == dest || NULL == src)
 {
  return NULL;
 }
 while ( *dest++ != '/0');
 dest -= 1;
 while ( ( *dest++ = *src++) != '/0');
}

 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:218402次
    • 积分:2702
    • 等级:
    • 排名:第13827名
    • 原创:21篇
    • 转载:147篇
    • 译文:0篇
    • 评论:11条
    最新评论