C/C++ memcpy實作
C/C++ memcpy實作
資料來源:https://mp.weixin.qq.com/s/lZ9SsObIMoncjs4ZoyLRlA
線上編譯:https://www.tutorialspoint.com/compile_c_online.php
Code:
#include <stdio.h> #include <string.h> void *sky_memecpy_1(void *dst, const void *str, int n) { if (NULL == dst || NULL == str || n <= 0) { return NULL; } char *pdst = (char *)dst; char *pstr = (char *)str; while (n --) { *pdst ++ = *pstr ++; } return dst; } void *sky_memecpy(void *dst, const void *str, int n) { if (NULL == dst || NULL == str || n <= 0) { return NULL; } char *pdst = (char *)dst; char *pstr = (char *)str; if (pdst > pstr && pdst < pstr + n) { pdst = pdst + n - 1; pstr = pstr + n - 1; while (n --) { *pdst -- = *pstr --; } } else { while (n --) { *pdst ++ = *pstr ++; } } return dst; } int main() { char str_1[100] = "heLlo,world"; char str_2[100] = "heLlo,world"; sky_memecpy_1(str_1+1,str_1,strlen(str_1)); printf("%s\n",str_1); sky_memecpy(str_2+1,str_2,strlen(str_2)); printf("%s\n",str_2); return 0; }