Today I saw the difference between the book and the memcpy and Memmove suddenly
Found that there are so different between the two previously only know that these functions are
Achieve the same functionality without touching it differently.
memcpy and Memmove are defined on MSDN as follows:
There is no difference from the statement of the two, so let's look at an example
When we need to copy all the strings of char* src= "ABCDE" to Dest
However, the SRC and dest in memory probably exist in this way:
Memory address low------> high
1 src dest2 1 2 3 4 5 6 3 ' / ' ] [ ][ ][ ][ ][ ][ ][ ]
SRC address is memory 1, destination address is memory 2
It is obvious that memory overlaps when we copy the character A to the third memory location
A will overwrite the third character in SRC memory This situation is undefined in memcpy however memmove
The right way to handle it.
Workaround, imagine when we first move the dest address dest+n-1 the SRC address to move src+n-1
This avoids the memory as it is copied from the last element of SRC to the dest.
Overlap causes the element coverage problem?
Below we give our own implementation according to memcpy and Memmove:
1#include <iostream>2 using namespacestd;3 4 void*memcopy (void*dest,Const void*src, size_t count)5 {6 if(dest==null| | src==NULL)7 returnNULL;8 Char* Dest= (Char*) dest;9 Const Char* Src= (Char*) src;Ten One intI=0; A - while(i<count) - { the*dest++=*src++; -i++; - } - + returndest; - } + A void*memmove (void*dest,Const void*src,size_t count) at { - if(dest==null| | src==NULL) - returnNULL; - - Char* Dest= (Char*) dest; - Const Char* Src= (Char*) src; in - intI=0; to if(src>dest) + { - while(I<count)//forward Copy the { **dest++=*src++; $i++;Panax Notoginseng } - } the Else + { Adest=dest+count-1;//Reverse Copy thesrc=src+count-1; + - while(i<count) $ { $*dest--=*src--; -i--; - } the } - Wuyi the - returndest; Wu } - About $ - voidMain () - { - Chardest[ the]; Amemset (dest,' /', the); + Char* src="memcpyteststring"; the intN; -cout<<"How many char-want to copy from SRC to Dest (memcpy):"; $Cin>>N; thecout<<"The dest string is:"<< (Char*) memcopy (dest,src,n) <<Endl; thecout<<"How many char-want to copy from SRC to Dest (memcpy):"; theCin>>N; thecout<<"The dest string is:"<< (Char*) Memmove (dest,src,n) <<Endl; - return; in}
Run:
A little note on memcpy and memmove