cfunctionmemmove

How to use and when is good use memmove in C?


I have two doubts about the use of memmove():

I hope I explained my doubts in a good way.

edit: I have to delete an element from the array, and then I want to shift the following elements of the deleted one on the left.


Solution

    1. memmove may be faster but it probably will never be slower than your own function for copying data around (it's usually coded in carefully crafted assembly to move stuff around in the most efficient way possible on the current architecture);
    2. it depends on what you want to do with that array... if you want to copy its content to another array arr will suffice (and, as the length parameter, you should do sizeof(*arr)*N where N is the number of elements to copy).

    By the way, if source and destination and the copy are nonoverlapping memcpy may be faster.

    I want to delete an element from the array and shift left the element of the same array.

    int arr[N];
    /* ... */
    /* Let's say you want to remove the element i (error checking on i omitted) */
    memmove(arr+i, arr+i+1, (N-i-1)*sizeof(*arr));
    /* or, if you prefer array indexing over pointer arithmetics: */
    memmove(&arr[i], &arr[i+1], (N-i-1)*sizeof(*arr));
    

    (sizeof(*arr) means "get the size of an element of the array")