【问题标题】:how to write a copy function for an array?如何为数组编写复制函数?
【发布时间】:2021-05-16 14:20:28
【问题描述】:

如何为大小为 2 的数组编写复制函数?使用c 我想要它,所以我可以将它传递给通用代​​码 这是定义:

/** Key element data type for map container */
typedef void *MapKeyElement;

这是我写的复制函数:

MapKeyElement gameCopyKey(MapKeyElement array_to_copy)
 {
if(!array_to_copy)
{
 
   return NULL ;
}
int** array=malloc(sizeof(**array));
if(!array)
{
return NULL;
}
int *tmp=(int*)array_to_copy;
  *array[0]= tmp[0];
  *array[1]= tmp[1];
return array;
}

但我不知道这是否是写入方式? 有人有想法吗?

【问题讨论】:

  • 至少int** array=malloc(sizeof(**array)); 看起来不对。分配array[0]array[1]应该是int** array=malloc(sizeof(*array) * 2);。也不要忘记在取消引用之前将元素初始化为某个有效地址。

标签: arrays c copy


【解决方案1】:

你必须告诉函数数组元素的大小。您可以通过将类型设为完整类型而不是 void 来做到这一点:

typedef WhateverMyElementTypeIs *MapKeyElement;

MapKeyElement CopyThisArray(MapKeyElement Array)
{
    MapKeyElement NewArray = malloc(2 * sizeof *NewArray);
    if (NewArray)
        memcpy(NewArray, Array, 2 * sizeof *NewArray);
    return NewArray;
}

或通过将大小传递给函数:

typedef void *MapKeyElement;

MapKeyElement CopyThisArray(MapKeyElement Array, size_t ElementSize)
{
    MapKeyElement NewArray = malloc(2 * ElementSize);
    if (NewArray)
        memcpy(NewArray, Array, 2 * ElementSize);
    return NewArray;
}

memcpy<string.h>中声明,size_t<stddef.h>中声明。

【讨论】:

    【解决方案2】:

    在 C 中无法避免从复制函数中复制的数据大小:它可以作为要复制的数据类型的属性或作为显式参数传递:

    void* copy2(void* array2, size_t szElement)
    {
        void* res = malloc(2*szElement);
        // do your NULL check here...
        memcpy(res, array2, 2*szElement);
        return res;
    }
    

    不过,您可以将计算大小的部分隐藏到宏中:

    #define COPY2(x) copy2((x), sizeof((x)[0]))
    

    此宏必须传递一个您要复制的特定类型的数组,而不是void*

    下面是如何使用这个宏:

    int ia[2] = {321, 789};
    int* ic = COPY2(ia);
    struct foo {
        char* a;
        char* b;
    } sa[2] = {
        {"hello", "world"},
        {"one", "two"}
    }, *sc = COPY2(sa);
    printf("%d %d\n", ic[0], ic[1]);
    printf("%s %s\n%s %s\n", sc[0].a, sc[0].b, sc[1].a, sc[1].b);
    

    注意COPY2(ia)COPY2(sa) 看起来是一样的,但它们传递copy2 不同的sizeof 值,具体取决于iasa 的元素类型。

    Demo.

    【讨论】:

      猜你喜欢
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 2017-01-18
      • 1970-01-01
      相关资源
      最近更新 更多