Step 0
Learn the syntax of memcpy in C++. The complete syntax is void *memcpy (void *destination, const void *source, size_t num);. Note that this function always copies num bytes and does not look for a terminating character in order to be as efficient as possible. Memcpy returns the destination array.
Step 1
Know that the pointers to the source and destination arrays are type-cast to a type of void. The size of the destination and source arrays should be at least num bytes to avoid overflows, although this is not required. Memmove should be considered as a safer approach if the source and destination overlap.
Step 2
Understand that the C++ memcpy function is kept in the cstring library. You may need to include the string.h header file to use memcpy.
Step 3
Look at the following complete program for some simple examples of how to use memcpy:
#include_<_stdio.h_>
#include_<_string.h_>
int main ()
{
__char string1[]="test string";
__char string2[80];
__memcpy (string2,string1,strlen(string1)+1);
__printf ("string1: %s\nstring2: %s\n",string1,string2);
__memcpy (string1,"",1);
__printf ("string1: %s\n",string1);
__return 0;
}
Observe the following output for this program:
string1: test string
string2: test string
string1:
The first use of memcpy copies the contents of string1 to the contents of string2. The second use of memcpy clears the contents of string1 by moving the null terminator character to the first position of string1.
Note: Please DO NOT copy-paste the code given in this post.
0 comments:
Post a Comment