I remember that when I saw the memcpy ()
function for the first time in the code, I did not understand what kind of unknown animal it was. No one even thought to write a comment that explains it (no, well, then you understand that it is logical .. not to write what printf
does in the comments). At the same time, several hundred were scattered throughout the code of these memcpy
. Right here are a handful of these functions, like clusters of ripe grapes hanging .. but how to eat them is not clear. Comments at best said something about copying, something about memory, buffer and other buzzwords.
So. memcpy()
function – from English. memory copy – copies the contents of a memory cell from one area to another; the cells must not overlap. Defined with #include <string.h>
memcpy(where, where, size);
For example:
memcpy(&k, &o, sizeof(struct r));
copies a chunk (a number of bytes) of size struct r
from memory area &o
to memory area &k
and returns its (&k
) address.
It is important that this is a function for copying non-intersecting arrays. You can’t do this:
[---- &o ----]
[---- &k ---]
Otherwise, the output will be bad. For example, let’s try to copy:
___&o___ | | 1234567890xxxxx |__ ___| &k
There will be this:
___&k___ | | 121212121212xxx
So this is a very dangerous feature. Here it is very easy to make a mistake with the range (size) of the copied and then you will find an error.
How to solve this problem if there is a need to copy intersecting cells? In addition to the memcpy
function in string.h
, there are a bunch of other memory manipulation functions, in particular:
void *memmove(void *, const void *, size_t);
It is the same as memcpy
, but the contents of the cells may overlap (intersect). Although it works slower than memcpy
String.x also has:
void *memchr(const void *, int, size_t);
search for the first occurrence of a specified character in an array
int memcmp(const void *, const void *, size_t);
compares arrays
void *memset(void *, int, size_t);
fills an array with the specified characters
No, well, there’s a lot of honey there. I won’t list everything. Read the manual, brothers.