-4

I m looking for how to write a function like memcpy. Method that copy integers or chars from one array to other. What i mean, its to use memcpy, without using it. But in my case it does not work.

void Memcpy( void *from, void *to, int dimension, int length ) {

   if(dimension == sizeof(char)){
      char *copyFrom = (char *)from;
      char *copyTo = (char *)to;

      for(int i = length; i < length; i++)
         copyTo[i] = copyFrom[i];
   }


   if(dimension == sizeof(int)){
      int *copyFrom = (int *)from;
      int *copyTo = (int *)to;

      for(int i = length; i < length; i++)
         copyTo[i] = copyFrom[i];
   }
}

{Thank you for help =)}

John J
  • 1
  • 2

2 Answers2

5
void copyOfArray( void *from, void *to, int dimension, int length ) {
     memcpy(to, from, dimension * length);
}
Petar Velev
  • 2,305
  • 12
  • 24
0

What you want is really achieved with memcpy, there is no need to reinvent it. For your convinience you can wrap it with copy_of_array or even wrap copy_of_array with copy2 (as long as arrays are staticaly allocated).

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

#define copy2(src, dst, count, shift) copy_of_array(src, dst, count, sizeof(src[0]), shift)

copy_of_array (void * src,
               void * dst,
               int    count,
               int    elem_size,
               int    shift)
{
  memcpy (dst, (char*)src + elem_size * shift, count * elem_size);
}

int main() {
  int i;
  int ione[4] = { 1, 2, 3, 4};
  int itwo[2] = { 0, 0 };
  char cone[4] = { 'a', 'b', 'c', 'd'};
  char ctwo[2] = { 'x', 'y' };
  copy_of_array(ione, itwo, 1, sizeof(int), 3);
  for (i=0; i<2; i++ )
    printf("%d ", itwo[i] );

  copy2(cone, ctwo, 1, 3);
  for (i=0; i<2; i++ )
    printf("%c ", ctwo[i] );
}
Alexander Dmitriev
  • 2,483
  • 1
  • 15
  • 20