C語言實現(xiàn)memcpy函數(shù)的使用示例
在 C 語言中,我們可以自己實現(xiàn) memcpy 函數(shù)來實現(xiàn)內(nèi)存數(shù)據(jù)的拷貝操作。memcpy 函數(shù)用于將指定長度的數(shù)據(jù)從源地址復(fù)制到目標(biāo)地址。
按字節(jié)拷貝實現(xiàn)memcpy
#include <stdio.h>
void* my_memcpy_byte(void* dst, const void* src, int n)
{
if (dst == NULL || src == NULL || n <= 0)
return NULL;
char* pdst = (char*)dst;
char* psrc = (char*)src;
//判斷目標(biāo)內(nèi)存區(qū)域和源內(nèi)存區(qū)域是否有重疊
if (pdst > psrc && pdst < psrc + n)
{
//如果有重疊,就從尾部開始遍歷
pdst = pdst + n - 1;
psrc = psrc + n - 1;
while (n--)
*pdst-- = *psrc--;
}
else
{
while (n--)
*pdst++ = *psrc++;
}
return dst;
}
int main(void)
{
char str[] = "HelloWorld";
char* str1 = &str[0];
char* str2 = &str[1];
my_memcpy_byte(str1, str2, 5);
printf("%s\n", str); //輸出elloWWorld
return 0;
}
按4字節(jié)拷貝實現(xiàn)memcpy
#include <stdio.h>
void* my_memcpy_byte(void* dst, const void* src, int n)
{
if (dst == NULL || src == NULL || n <= 0)
return NULL;
int* pdst = (int*)dst;
int* psrc = (int*)src;
char* pdstTemp = NULL;
char* psrcTemp = NULL;
int byte4Count = n / 4; //有多少個4字節(jié),按4字節(jié)拷貝
int byteCount = n % 4; //剩余字節(jié)數(shù)按字節(jié)拷貝
//判斷目標(biāo)內(nèi)存區(qū)域和源內(nèi)存區(qū)域是否有重疊,如果有從后往前,如果沒有從前往后
if (pdst > psrc && pdst < (char*)psrc + n)
{
pdstTemp = (char*)pdst + n - 1;
psrcTemp = (char*)psrc + n - 1;
while (byteCount--)
{
*pdstTemp-- = *psrcTemp--;
}
pdstTemp++;
psrcTemp++;
pdst = (int*)pdstTemp;
psrc = (int*)psrcTemp;
pdst--;
psrc--;
while (byte4Count--)
{
*pdst-- = *psrc--;
}
}
else
{
while (byte4Count--)
{
*pdst++ = *psrc++;
}
pdstTemp = (char*)pdst;
psrcTemp = (char*)psrc;
while (byteCount--)
{
*pdstTemp++ = *psrcTemp++;
}
}
return dst;
}
int main(void)
{
char str[] = "HelloWorld";
char* str1 = &str[0];
char* str2 = &str[1];
my_memcpy_byte(str1, str2, 1);
printf("%s\n", str);
return 0;
}
Tips
對比字節(jié)拷貝,4字節(jié)拷貝速度是提高不少。
但是需要注意,void *dst, const void *src這兩個參數(shù)是需要按4字節(jié)對齊的,如果本身不是4字節(jié)對齊,按4字節(jié)拷貝效率也會變低。
到此這篇關(guān)于C語言實現(xiàn)memcpy函數(shù)的使用示例的文章就介紹到這了,更多相關(guān)C語言memcpy函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言編寫實現(xiàn)學(xué)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語言編寫實現(xiàn)學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-07-07
C++關(guān)于類結(jié)構(gòu)體大小和構(gòu)造順序,析構(gòu)順序的測試詳解
這篇文章主要介紹了C++類結(jié)構(gòu)體大小和構(gòu)造順序,析構(gòu)順序的測試,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
C++面試題之結(jié)構(gòu)體內(nèi)存對齊計算問題總結(jié)大全
這篇文章主要給大家總結(jié)了關(guān)于C++面試題中結(jié)構(gòu)體內(nèi)存對齊計算問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),通過這些介紹的內(nèi)容對大家在面試C++工作的時候,會有一定的參考幫助,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-08-08

