📜  C / C++中的memmove()

📅  最后修改于: 2021-05-30 10:29:49             🧑  作者: Mango

memmove()用于将一个内存块从一个位置复制到另一个位置。在字符串.h中声明

// Copies "numBytes" bytes from address "from" to address "to"
void * memmove(void *to, const void *from, size_t numBytes);

下面是一个示例C程序,用于显示memmove()的工作方式。

C
/* A C program to demonstrate working of memmove */
#include 
#include 
 
int main()
{
    char str1[] = "Geeks"; // Array of size 100
    char str2[] = "Quiz"; // Array of size 5
 
    puts("str1 before memmove ");
    puts(str1);
 
    /* Copies contents of str2 to sr1 */
    memmove(str1, str2, sizeof(str2));
 
    puts("\nstr1 after memmove ");
    puts(str1);
 
    return 0;
}


C
// Sample program to show that memcpy() can loose data.
#include 
#include 
int main()
{
    char csrc[100] = "Geeksfor";
    memcpy(csrc + 5, csrc, strlen(csrc) + 1);
    printf("%s", csrc);
    return 0;
}


C
// Sample program to show that memmove() is better than
// memcpy() when addresses overlap.
#include 
#include 
int main()
{
    char str[100] = "Learningisfun";
    char *first, *second;
    first = str;
    second = str;
    printf("Original string :%s\n ", str);
     
    // when overlap happens then it just ignore it
    memcpy(first + 8, first, 10);
    printf("memcpy overlap : %s\n ", str);
 
    // when overlap it start from first position
    memmove(second + 8, first, 10);
    printf("memmove overlap : %s\n ", str);
 
    return 0;
}


输出
str1 before memmove 
Geeks

str1 after memmove 
Quiz

memcpy()有何不同?

memcpy()只是将数据从一个位置一个一个地复制到另一个位置。另一方面,memmove()首先将数据复制到中间缓冲区,然后再从缓冲区复制到目标。
当字符串重叠时,memcpy()会导致问题。

例如,考虑下面的程序。

C

// Sample program to show that memcpy() can loose data.
#include 
#include 
int main()
{
    char csrc[100] = "Geeksfor";
    memcpy(csrc + 5, csrc, strlen(csrc) + 1);
    printf("%s", csrc);
    return 0;
}
输出
GeeksGeeksfor

由于输入地址重叠,因此上述程序将覆盖原始字符串并导致数据丢失。

考虑以下程序,以了解发生重叠时memcpy和memmove函数之间的区别。

C

// Sample program to show that memmove() is better than
// memcpy() when addresses overlap.
#include 
#include 
int main()
{
    char str[100] = "Learningisfun";
    char *first, *second;
    first = str;
    second = str;
    printf("Original string :%s\n ", str);
     
    // when overlap happens then it just ignore it
    memcpy(first + 8, first, 10);
    printf("memcpy overlap : %s\n ", str);
 
    // when overlap it start from first position
    memmove(second + 8, first, 10);
    printf("memmove overlap : %s\n ", str);
 
    return 0;
}
输出
Original string :Learningisfun
 memcpy overlap : LearningLearningis
 memmove overlap : LearningLearningLe
 

如您所见,只要有重叠发生(例如,当第一个指针移动到字符’i’时),就可以使用memmove函数,然后从头开始打印第一个指针(输出Le),但是对于memcpy函数,它只是忽略是否存在是重叠的,只是继续前进。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”