memcpy

The memcpy function copies the content of a memory block into another memory location. It doesn't check if the destination memory buffer has enough space to receive the copy, so it should be used with care. This function is declared in string.h, and has a behavior similar to strcpy. However, it doesn't require that the memory block contains only characters. It also doesn't require that it be NULL terminated.

The memcpy function requires three arguments. The first argument is a pointer to the destination memory. The second argument is a pointer to the source memory block. The third argument is the size of the block we want to copy, given in a integral variable of type size_t.

Notice also that memcpy was not designed to copy between overlapping blocks of memory. In this case the behavior in undefined.

The following code shows an example of memcpy use:

#include        
#include        

#define MEM_SIZE 10

int main()
{
        int source[MEM_SIZE];
        int dest[MEM_SIZE];
        int i;
        for (i=0; i<MEM_SIZE; i++) {
                source[i] = i+1;
        }
        memcpy(dest, source, MEM_SIZE*sizeof(int));
        for (i=0; i<MEM_SIZE; i++) {
                printf("dest[i] = %d\n", dest[i]);
        }
        return 0;
}
Article created on 2008-08-19 22:01:51

Post a comment