views:

83

answers:

3

Hi folks,

I fall in some problem.

I need to write some function like memcpy(void*, const void*), which its signature should be:

void arrayCopy(void *dest, int dIndex, const void *src, int sIndex, int len)

I noticed that, in many implementation of memcpy, we cast void* to char*, but I think this is not the case of me, as the arrayCopy function needed to be used on arrays of many types including structs.

So, how can I accomplish this?

EDIT: the source code might be something like that:

#include <stdio.h>
#include <string.h>

void arrayCopy(void *, int, const void *, int, int, size_t);

int main(void)
{
    int i;
    int dest[10] = {1};
    int src [] = {2, 3, 4, 5, 6};

    arrayCopy(dest, 1, src, 0, 5, sizeof(int));

    for (i=0; i<10; i++) printf("%i\n", dest[i]);

    return 0;
}

void arrayCopy(void *dest, int dIndex, const void *src, int sIndex, int len, size_t size)
{
    char *cdest = (char*) dest;
    const char *csrc = (char*) src;
    int i;

    len *= size;

    if (dest == src)
    {
        printf("Same array\n");
    }else
    {
        cdest += (dIndex * size);
        csrc += (sIndex * size);
        for (i=0; i<len; i++)
            *cdest++ = *csrc++;
    }
}

Thanks.

+1  A: 

"char * " is just a bunch bytes, everything in C is ultimately bytes - you can cast a pointer to any data structure to char* (you will also need to know the size in memory of the structure)

Martin Beckett
char* is ptr of the same size as int*, but *int_var takes 4 bytes while *char_var takes 1 byte (on 4byte systems)
Mohammed
The correct code is above. thanks
Mohammed
+2  A: 

The function must have an element-size info, eg:

void *arrayCopy(void *dest, size_t di,const void *src, size_t si, size_t num, size_t esize)
{
  char *cdest = (char*) dest;
  const char *csrc = (char*) src;
  return memcpy( &cdest[esize*di], &csrc[esize*si], esize*num );
}
...
arrayCopy(dest, 1, src, 0, 5, sizeof*src);
+2  A: 

You cannot work with objects of type void. The Standard doesn't allow that. So you need to cast the void away, and the best type to use is unsigned char. There's a guarantee by the Standard that unsigned char can access all bits of any other type representable in your system.

pmg