문제

Difference: If there is an overlap, use memmove in place of memcpy

Q: Could you provide a practical scenario of any C lib function where an overlap happens so memmove is used in place of memcpy?

도움이 되었습니까?

해결책

Here's one:

// len => array length, idx => index where we want to remove
void removeAt(int* array, size_t* len, size_t idx)
{
    // copy next values to replace current
    // example: {1, 2, 3, 4} => {1, 3, 4}
    //              ^ remove
    memmove(&array[idx], &array[idx+1], (--(*len) - idx) * sizeof(int));
}

Edit: Regarding this appearing in the implementation of a C stdlib function, that would be a bit more difficult to find, since each implementation can do their own thing, and most stdlib functions require that the arguments do not overlap.

다른 팁

For example you need to insert an element in the middle of an array (in-place). This requires shifting the elements from the insertion points onwards by one place. This can be done with memmove() but not with memcpy().

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top