1. 程式人生 > >模擬實現memcpy 與 memmove

模擬實現memcpy 與 memmove

方法 包含 指向 style sizeof num const con emc

模擬實現memcpy 與 memmove 1.str系列的函數只能處理字符串——>必須帶有‘\0‘
2.memcpy內存處理函數:不涉及‘\0‘,需要包含頭文件 string.h
3.source的內存不能超過destanation的內存大小
4.存在緩沖區的重合問題,要保證destanation指向有效的區域:可以用從右往左拷貝的方法
//memmove可以解決mencoy的緩沖區重合的問題
 1 #include<stdio.h>
 2 #include<assert.h>
 3 void Memcpy(void* destanation, const
void* source, size_t num) 4 { 5 assert(destanation != 0); 6 assert(source != 0); 7 char* dest = (char*)destanation; 8 char* sour = (char*)source; 9 for (size_t i = 0; i < num; i++) 10 { 11 dest[i] = sour[i]; 12 } 13 return destanation; 14 } 15 void Memmove(void* destanation, const
char* source, size_t num) 16 { 17 assert(destanation != 0); 18 assert(source != 0); 19 char* dest = (char*)destanation; 20 char* sour = (char*)source; 21 //兩種情況: 22 if (sour<dest&&sour + num>dest) 23 { 24 //1.緩沖區重合就從後往前拷貝 25 for (int i = num - 1; i >= 0; --i) 26 {
27 dest[i] = source[i]; 28 } 29 } 30 else 31 { 32 //2.緩沖區沒重合,代碼和memcpy一樣 33 Memcpy(destanation, source, num); 34 } 35 } 36 int main() 37 { 38 int arr1[4] = { 1,2,3,4 }; 39 int arr2[4] = { 0 }; 40 Memcpy(arr1, arr2, sizeof(arr1)); 41 for (int i = 0; i < sizeof(arr1) / sizeof(int); i++) 42 { 43 printf("%d",arr2[i]); 44 } 45 return 0; 46 }

模擬實現memcpy 與 memmove