作用是**拷贝一定长度的内存的内容,**函数原型如下:
void* memmove( void* dest, const void* src, std::size_t count );
// void * memmove ( void * destination, const void * source, size_t num ); // 另一种形式的声明
函数参数定义如下:
参数名字 | 意义 |
---|---|
dest | 目的地的内存地址的指针 |
src | 源内容内存地址的指针 |
count | 要复制的字节数 |
示例代码如下:
// 代码基本都是使用 C 风格函数
#include
#include
#include
// 打印数组函数
void print_array(int* arr, int n) {
if (arr == NULL) { // C语言用 NULL,C++11用nullptr
return;
}
for (int i = 0; i < n; i++){
printf("%d ", arr[i]);
}
printf("\n");
}
// int 类型对象占 4 个字节
void int_arr_copy_test() {
int arr[] = {1,2,3,4,5,6,7,8,9}; // int 数组
print_array(arr, 9);
// std::memmove(arr + 4, arr + 3, sizeof(int)); // 从 [4, 5, 6] 复制到 [5, 6, 7]
std::memmove(arr + 4, arr + 3, 4); // 从 [4, 5, 6] 复制到 [5, 6, 7]
print_array(arr, 9);
}
// char 类型对象占 1 个字节
void char_arr_copy_test() {
char str1[] = "1234567890"; // char 数组
puts (str1);
// std::cout << str << '\n';
std::memmove(str1 + 4, str1 + 3, 4); // 从 [4, 5, 6] 复制到 [5, 6, 7]
puts (str1);
}
int main()
{
int_arr_copy_test();
char_arr_copy_test();
}
程序编译运行后输出如下:
puts
函数功能是将字符串输出到屏幕。与 printf
函数相比,puts 使用更简单,且系统会自动在其后添加一个换行符;但是 puts() 后面的参数只能是字符指针变量或字符数组,即括号中除了字符指针变量名或字符数组名之外什么都不能写。
类型 | 32 位机占用字节数 | 64 位机占用字节数 |
---|---|---|
char | 1 字节 | 1 字节 |
short | 2 字节 | 2 字节 |
int | 4 字节 | 4 字节 |
long | 4 字节 | 8 字节 |
memcpy
和 memmove
函数作用是一样的,唯一的区别是,当内存发生局部重叠的时候,memmove 保证拷贝的结果是正确的,memcpy 不保证拷贝的结果的正确。示例代码如下:
/* memcpy example */
#include
#include
struct {
char name[40];
int age;
} person, person_copy;
int main ()
{
char myname[] = "Pierre de Fermat";
/* using memcpy to copy string: */
memcpy ( person.name, myname, strlen(myname)+1 );
person.age = 46;
/* using memcpy to copy structure: 源地址和目的地址没有重合*/
memcpy ( &person_copy, &person, sizeof(person) );
printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );
return 0;
// 程序输出结果:person_copy: Pierre de Fermat, 46
}
memmove
的实现如下:
void *mymemmove(void *dest, const void *src, size_t n)
{
char temp[n];
int i;
char *d = dest;
const char *s = src;
for (i = 0; i < n; i++)
temp[i] = s[i];
for (i = 0; i < n; i++)
d[i] = temp[i];
return dest;
}