In the previous article, we introduced str series functions, but str series functions can only be used for strings, not for any type. Then in this article, we introduced functions starting with mem, which are applicable to any type.
memcpy: copy function
Function prototype:
void * memcpy ( void * destination, const void * source, size_t num );
Function simulation implementation:
void *my_memcpy(void *dest, void *src,int count)
{
char *pdest = (char*)dest;
const char *psrc = (const char*)src;
while (count--)
{
*pdest = *psrc;//One byte one byte copy
pdest++;
psrc++;
}
return dest;
}
int main()
{
int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int arr2[10];
int i = 0;
int sz = sizeof(arr1);
my_memcpy(arr2, arr1, sz);
for (i = 0; i < 10; i++)
{
printf("%x", arr1[i]);
}
printf("\n");
system("pause");
return 0;
}
memmove: copy
We just mentioned a copy function memcpy, but in fact, the function is flawed. It does not consider the problem of memory overlap. At the same time, memcpy cannot copy the same string.
So let's analyze how memmove considers memory overlap?
Let's use a picture to analyze:
void * memmove ( void * destination, const void * source, size_t num );
Function simulation implementation:
void *my_memmove(void *dest, void *src, int count)
{
char *pdest = (char*)dest;
const char *psrc = (const char*)src;
if ((pdest > psrc) && (pdest < psrc + count))
{
//Copy back to front
while (count--)
{
*(pdest + count) = *(psrc + count);
}
}
else
{//Copy from front to back
while (count--)
{
*pdest++ = *psrc++;
}
}
return dest;
}
int main()
{
int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int arr2[10];
int i = 0;
int sz = sizeof(arr1);
my_memmove(arr1+2, arr1, 16);
for (i = 0; i < 8; i++)
{
printf("%x ", arr1[i]);
}
printf("\n");
system("pause");
return 0;
}
memset: the num byte content in the string is set to value
Function prototype:
void * memset ( void * ptr, int value, size_t num );
The parameters here should be explained in particular:
1. value: the value to be initialized
2. num: the number of bytes to be set to this value. (to multiply by type size)
Function simulation implementation:
void *my_memset(void * dest, int n, size_t count)
{
void *ret = dest;
while (count--)
{
*(char*)dest = n;
dest = (char*)dest + 1;
}
return ret;
}
int main()
{
int arr1[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int arr2[10];
int i = 0;
int sz = sizeof(arr1);
my_memset(arr2, 0, 10*sizeof(int));
for (i = 0; i < 8; i++)
{
printf("%x ", arr2[i]);
}
printf("\n");
system("pause");
return 0;
}