C language function memory operation

memcpy:

the memcpy * void (void * Where do you want, Source const void *, size_t NUM); 

Source to copy data from dest, size_t is noted that the number of bytes, and regardless of type. For example, you can call:
int main()
{
    int p[3] = { 4,4,4 }, q[3] = { 2,2,2 };
    memcpy(p, q, 3 * sizeof(int));
    return 0;
}

Wherein a length of 3 to specify an int, a total of 12 bytes copied.

 

memmove:

void * memmove (void * destination, const void * source, size_t num); 

and memcpy functionally similar, but the internal function will prevent data erase original position during replication, such as for an array of p we memcpy (p + 2, p , 5 * sizeof (int)) ; we can see that the first copy int time, the position of the third p [2] of the data replication.

 

 

 Memcpy memmove difference with this is that memory may be identified to overlap the data copied from the back in this case, so as not to generate duplicate data results in lost data.

The principle is inside a if else statements, whether there is an overlap of memory two cases were dealt with separately. Check whether the memory of which is coincident with a macro __np_anyptrlt. c language codes are as follows:

#include <stddef.h> /* for size_t */
void *memmove(void *dest, const void *src, size_t n)
{
    unsigned char *pd = dest;
    const unsigned char *ps = src;
    if (__np_anyptrlt(ps, pd))
        for (pd += n, ps += n; n--;)
            *--pd = *--ps;
    else
        while(n--)
            *pd++ = *ps++;
    return dest;
}

 

 

memcpr:

void * memcpy (void * destination, const void * source, size_t num); 
both compare the size of each byte (in ASCII size comparison, the 'g' is greater than 'G' of greater than uppercase letter lowercase)
Note : '0': 48, ' A': 65, 'a': 97

 

 

 

memset:

void * memset (void * ptr, int value, size_t num); 
a byte ptr num after filling to value.

 

/* memset example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] = "almost every programmer should know memset!";
  memset (str,'-',6);
  puts (str);
  return 0;
}

 

 

 





Guess you like

Origin www.cnblogs.com/FdWzy/p/12466479.html