memmove
- Move block of memory
- Copies the values of num bytes from the location pointed by source to the memory block pointed by destination. Copying takes place as if an intermediate buffer were used, allowing the destination and source to overlap.
- The underlying type of the objects pointed by both the source and destination pointers are irrelevant for this function; The result is a binary copy of the data.
- The function does not check for any terminating null character in source - it always copies exactly num bytes.
- To avoid overflows, the size of the arrays pointed by both the destination and source parameters, shall be at least num bytes.
- 從 source 所指向的對象複製 num 個字節到 destination 所指向的對象。兩個對象都被轉譯成 unsigned char 的數組。對象能夠重疊:如同複製字符到臨時數組,再從該數組到 destination 通常發生複製。
- 從 source 複製 num 個字符到 destination,可是在重疊內存塊這方面,memmove() 是比 memcpy() 更安全的方法。若是目標區域和源區域有重疊的話,memmove() 可以保證源串在被覆蓋以前將重疊區域的字節拷貝到目標區域中,複製後源區域的內容會被更改。若是目標區域與源區域沒有重疊,則和 memcpy() 函數功能相同。
- 若出現 destination 數組末尾後的訪問則行爲未定義。
- 若 destination 或 source 爲空指針則行爲未定義。
void * memmove ( void * destination, const void * source, size_t num );
Parameters
destination
- Pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*.
- 指向用於存儲複製內容的目標數組,類型強制轉換爲 void* 指針。
- 指向複製目的對象的指針
source
- Pointer to the source of data to be copied, type-casted to a pointer of type const void*.
- 指向要複製的數據源,類型強制轉換爲 void* 指針。
- 指向複製來源對象的指針
num
- Number of bytes to copy.size_t is an unsigned integral type.
- 要被複制的字節數。
- 要複製的字節數
Return Value
- destination is returned.
- 該函數返回一個指向目標存儲區 destination 的指針。
- 返回 destination 的副本,本質爲更底層操做的臨時內存地址,在實際操做中不建議直接使用此地址,操做完成之後,真正有意義的地址是destination自己。
Example
//
// Created by zhangrongxiang on 2018/2/10.
//
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char str[32] = "I am your GOD";
char str2[32] = "Hello World";
char str3[] = "void * memmove ( void * destination, const void * source, size_t num );";
memmove(str2, str, strlen(str));
printf("%s\n", str2);//I am your GOD
memmove(str2, "hi\0hi", sizeof(str2));
printf("%s\n", str2);//hi
printf("%c%c%c%c\n", str2[3], str2[4], str2[5], str2[6]);//hi\0\0
memmove(str, str3, sizeof(str) - 1);
for (int i = 0; i < sizeof(str); ++i) {
printf("%c", str[i]);
}//void * memmove ( void * destina%
/////////////////////////////////////////////////////////////////////
char str4[] = "1234567890";
puts(str4);//1234567890
memmove(str4 + 4, str4 + 3, 3); // 從 [4,5,6] 複製到 [5,6,7]
puts(str4);//1234456890
////////////////////////////////////////////////////////////////////
// 設置分配的內存的有效類型爲 int
int *p = malloc(3 * sizeof(int)); // 分配的內存無有效類型
int arr[3] = {1, 2, 3};
memmove(p, arr, 3 * sizeof(int)); // 分配的內存如今擁有有效類型
printf("%d%d%d\n", p[0], p[1], p[2]);//123
printf("%d%d%d\n", *p, *(p + 1), *(p + 2));//123
return 0;
}
文章參考
轉載註明出處