My memmove



Description

Implement a function char* my_memmove(char *dst, const char *src, unsigned int n).

Detail

See main.cpp.

Try NOT to use another memory/array to do this, just do it in the array

Sample Input

Input guarantees that the length won't cause overflow.

abcdefghijklmnopqrstuvwxyzabcde
0 5 10
Sample Output

abcdeabcdefghijpqrstuvwxyzabcde
Hint

memmove is a function from <string.h>, you can see the reference here.

In a word, it's a function like strncpy. If you don't know it, you must know strcpy, a not really safe function. strncpy can copy cstring as strcpy, but you can set a maximum size to copy, which means you can avoid overflow using this (It's safer!). See the reference here.

What's the differences?

In standard library, the source and the destination strncpy can't overlap(重叠). And, strncpy will check the null-character('\0'), but memmove won't.

Then?

Here, you are going to implement one memmove by yourself.

Some of you guys may be smart and may try to use #define my_memmove memmove to do the trick, but it seems that <string.h> or <cstring> are banned here. Oh, what a bad news!

Anyway, happy coding!
main函数:

#include <cstdio>

#include "my_memmove.hpp"
#include "ban_string.h"

int main() {
  char buf[32] = {};
  scanf("%31s", buf);

  int src_offset = 0, dst_offset = 0, copy_size = 0;
  scanf("%d%d%d", &src_offset, &dst_offset, &copy_size);

  my_memmove(buf + dst_offset, buf + src_offset, copy_size);

  printf("%-31s\n", buf);

  return 0;
}
解答:
char* my_memmove(char *dst, const char *src, unsigned int n)
{
  if(dst<src)//从开头开始复制;
    for(int i=0;i<n;++i)
      dst[i]=src[i];
  else
  {
   src += n;  
       dst += n;   
       for (int i= 0; i < n; i++)  
       {   
          src --;   
          dst --;   
          *dst = *src;  
       }   
    }  
     return dst; 
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值