【问题标题】:Swap items of void* pointer array without memcpy in C在C中交换没有memcpy的void *指针数组的项目
【发布时间】:2013-05-08 17:26:13
【问题描述】:

我正在写一些学校项目,我需要交换两项 void* 指针数组。我可以用下面的代码来做到这一点:

void swap(void *base, int len, int width)
{
    void *p = malloc(width);

    memcpy(p,base,width);
    memcpy(base,(char*)base+width,width);
    memcpy((char*)base+width,p,width);

    free(p);
}

但我需要在没有 memcpy 的情况下交换项目,只需要使用 malloc、realloc 和 free。这可能吗?

谢谢

【问题讨论】:

  • 与其复制内存,不如直接交换地址?
  • 我已经尝试过了,但我认为 void* 数组是不可能的......如果可能的话,你能在这里发布一些代码吗?
  • void 是您的原生长度无符号整数。只需将其转换或将其用作要交换的指针算术即可。除非您使用 free(),否则您不会丢失这些变量。或者如果你使用智能指针你会输?

标签: c pointers memory


【解决方案1】:

为什么不这样交换呢?:

void swap(void *v[], int i, int j)
{
    void *temp;

    temp = v[i];
    v[i] = v[j];
    v[j] = temp;
}

和 qsort 一样(交换数组中的元素):

void sort(void *v[], int left, int right, int (*comp)(const void *, const void *))
{
    int i, last;

    if (left >= right) return;
    swap(v, left, (left + right) / 2);
    last = left;
    for (i = left + 1; i <= right; i++) {
        if ((*comp)(v[i], v[left]) < 0)
            swap(v, ++last, i);
    }
    swap(v, left, last);
    sort(v, left, last - 1, comp);
    sort(v, last + 1, right, comp);
}

【讨论】:

  • 是的,就是这样,非常感谢。我太拘泥于老师关于 free、malloc 和 realloc 的话。
【解决方案2】:

数组内容可以就地交换,仅使用char 作为临时变量。

void swap(void *base, int len, int width)
{
  int i;
  char t;

  for (i = 0; i < width; i++)
  {
    t = base[i];
    base[i] = base[i + width];
    base[i + width] = t;
  }
}

【讨论】:

    猜你喜欢
    • 2013-07-09
    • 2021-01-15
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-08
    相关资源
    最近更新 更多