不要使用庫函數,寫出void *memcpy(void *dst, const void *src, size_t count),其中dst是目標地址,src是源地址。

來源:互聯網
上載者:User

拷貝的時候要注意源記憶體位址和目的地址之間的關係,就是源記憶體位址和目標地址是否交叉。

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");}

以上例子為測試第二種情況的案例。如果不正確之處,希望給予點評。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.