I have two doubt about 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.
C library function - memmove() The C library function void *memmove(void *str1, const void *str2, size_t n) copies n characters from str2 to str1, but for overlapping memory blocks, memmove() is a safer approach than memcpy().
The memmove function copies n characters from the source to the destination object. In memmove before copying the characters from source to destination object first copied the n character from source to the temporary array, after that copy the n character from the temporary array to the destination object.
"memcpy is more efficient than memmove." In your case, you most probably are not doing the exact same thing while you run the two functions. In general, USE memmove only if you have to. USE it when there is a very reasonable chance that the source and destination regions are over-lapping.
The memcpy copy function shows undefined behavior if the memory regions pointed to by the source and destination pointers overlap. The memmove function has the defined behavior in case of overlapping. So whenever in doubt, it is safer to use memmove in place of memcpy.
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);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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With