拷貝的時候要注意源記憶體位址和目的地址之間的關係,就是源記憶體位址和目標地址是否交叉。
1,如果沒有交叉的情況,那直接迴圈拷貝就可以了。
2,如果有交叉的情況,交叉的情況也分為兩種
第一種:
這種情況是:src>=dst&&src<=dst+count-1
第二種:
這種情況就是:dst>src&&dst<src+count-1.
下面以數組:int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};為例,進行:memcpy(a, a+4, sizeof(int)*6);
第一種情況:
第二種情況:
由圖中的結果可以看出,第一種交叉情況和沒有交叉的情況一樣,直接迴圈拷貝就可以。但是如果有交叉的情況就要從源地址的最後一個位元組從前到後進行拷貝。
下面給出程式,只是參考
#include<stdio.h>void *memcpy(void *dst,const void *src,size_t count){char *p_dst=(char*)(dst);char *p_src=(char*)(src);unsigned int i;if(dst>src&&(char*)dst<=((char*)src+count-1))//如果p_dst=p_src那直接拷貝就可以了, { //如果p_dst=p_src+count-1,說明還有一個重疊, while(count){*(p_dst+count-1)=*(p_src+count-1);count--;}}else{for(i=0;i<count;i++)*(p_dst+i)=*(p_src+i);}return dst;}void main(){int arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};memcpy(arr+4,arr,sizeof(int)*6);for(int i=0;i<10;i++)printf("%d\t",arr[i]);printf("\n");}
以上例子為測試第二種情況的案例。如果不正確之處,希望給予點評。