Raea6789
Raea6789

Reputation: 141

how to write a copy function for an array?

How to write a copy function for an array of size 2? using c I want it so i can pass it to a generic code this is the define:

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

this is the copy function that i wrote:

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;
}

but i don't know if it's the write way to do it or not ? does anyone have an idea?

Upvotes: 0

Views: 52

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727067

There is no way in C to avoid the size of data being copied from the copying function: it is passed either as a property of the data type that you want to copy, or as an explicit argument:

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

You could hide the part that figures out the size into a macro, though:

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

This macro must be passed an array of a specific type that you are copying, not a void*.

Here is how you would use this macro:

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);

Note how COPY2(ia) and COPY2(sa) look the same, but they pass copy2 different sizeof values based on the element type of ia vs. sa.

Demo.

Upvotes: 1

Eric Postpischil
Eric Postpischil

Reputation: 224511

You must tell the function what size the array elements are. You can do this either by making the type a complete type rather than void:

typedef WhateverMyElementTypeIs *MapKeyElement;

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

or by passing the size to the function:

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 is declared in <string.h>, and size_t is declared in <stddef.h>.

Upvotes: 2

Related Questions