memcpy
- void* memcpy ( void* destination, const void* source, size_t num );
- 作用:按字節進行拷貝
- 參數說明:
- destination:目標數組
- source:源數組
- num:需要拷貝的字節數
- 返回值:destination
官方說明:複製內存塊
將num bytes的值從源指向的位置直接複製到目標指向的內存塊。源指針和目標指針指向的對象的基本類型與此函數無關;結果是數據的二進制副本。函數不檢查源中是否有任何終止的空字符-它總是精確地複製num字節。爲了避免溢出,目標參數和源參數指向的數組大小至少應爲num字節,並且不應重疊(對於重疊的內存塊,memmove是一種更安全的方法)。
測試程序
char *src = "hello!";
char dst[10];
memcpy(dst, src, strlen(src)+1);
puts(dst);
output:
hello!
模擬實現memcpy
void * mymemcpy(void * destination, const void * source, size_t num){
assert(destination);
assert(source);
void* copdst = destination;
while (num){
*(char*)destination = *(char*)source;
destination = (char*)destination + 1;
source = (char*)source + 1;
num--;
}
return copdst;
}
memmove
- void * memmove ( void * destination, const void * source, size_t num );
- 作用:將num個字節的值從一個數組中拷貝到另一個數組中
- 參數說明:
- destination:目標數組
- source:源數組
- num:需要移動的字節數
- 返回值:destination
官方說明:將num bytes的值從源指向的位置複製到目標指向的內存塊。複製就像使用了中間緩衝區一樣進行,允許目標和源重疊。源指針和目標指針指向的對象的基本類型與此函數無關;結果是數據的二進制副本。函數不檢查源中是否有任何終止的空字符-它總是精確地複製num字節。爲避免溢出,目標參數和源參數所指向的數組大小至少應爲num字節。
測試程序
char dst[30] = "destination";
memmove(dst + 3, dst, strlen(dst));
puts(dst);
output:
desdestination
模擬實現memmove
void * mymemmove(void * destination, const void * source, size_t num){
assert(destination);
assert(source);
void *copydst = destination;
if (destination <= source || (char *)destination >= ((char *)source + num)){
while (num){
*(char*)destination = *(char*)source;
destination = (char*)destination + 1;
source = (char*)source + 1;
num--;
}
}
else{
destination = (char*)destination + num - 1;
source = (char*)source + num - 1;
while (num){
*(char*)destination = *(char*)source;
destination = (char*)destination - 1;
source = (char*)source - 1;
num--;
}
}
return copydst;
}