在C中如何使用以及何时使用memmove? [英] How to use and when is good use memmove in C?

查看:64
本文介绍了在C中如何使用以及何时使用memmove?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于使用 memmove() ,我有两个疑问:

I have two doubt about use of memmove():

  • 何时最好使用此函数而不使用另一个函数(即创建的自己的函数)?我不确定我是否理解正确.
  • 该函数的签名为 void * memmove(void * dest,const void * src,size_t n).如果我有一个简单的数组 arr [N] ,如何将其放入调用的函数中?arr [N]或& arr [N]?区别在于数组是使用初始大小声明还是像指针一样声明?我有这个疑问,因为我看到了很多在两个地方都使用的示例.
  • When is preferable use this function instead of use another function (i.e. a created own function)? I’m not sure I have understood properly.
  • The signature of the function is void *memmove(void *dest, const void *src, size_t n). If I have a simple array arr[N], how can I put it into the called function? arr[N] or &arr[N]? The difference is if the array is declared with an initial size or like a pointer? I have this doubt because I saw many example where is used both.

我希望我能很好地解释我的疑问.

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.

推荐答案

  1. memmove 可能会更快,但它可能永远不会比您自己的数据复制功能慢(它通常是经过精心设计的汇编代码,可以在当前环境中以最有效的方式移动内容建筑);
  2. 这取决于您要对该数组执行的操作...如果要将其内容复制到另一个数组,则 arr 就足够了(并且,作为length参数,您应该执行 sizeof(* arr)* N ,其中N是要复制的元素数).
  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).

顺便说一句,如果源和目标以及副本不重叠,则 memcpy 可能会更快.

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)的意思是获取数组元素的大小")

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

这篇关于在C中如何使用以及何时使用memmove?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆