26

What is the best way to duplicate an integer array? I know memcpy() is one way to do it. Is there any function like strdup()?

7
  • 1
    strdup relies on a null terminator, which int arrays don't have. What's wrong with memcpy? Nov 27, 2011 at 16:40
  • Ya that will do. I wanted know if I can do it in one go like the way it happens for strings using strdup(). Nov 27, 2011 at 16:41
  • Did you allocate the array with malloc, int x* = (int *) malloc(100) or just declare it int x[100]; ??
    – EvilTeach
    Nov 27, 2011 at 16:42
  • @Chris: I got the point I have to write my own using memcpy as KSB suggested below. Nov 27, 2011 at 16:44
  • @EvilTeach: I used malloc. I mean I would. Nov 27, 2011 at 16:45

2 Answers 2

37

There isn't, and strdup isn't in the standard, either. You can of course just write your own:

int * intdup(int const * src, size_t len)
{
   int * p = malloc(len * sizeof(int));
   memcpy(p, src, len * sizeof(int));
   return p;
}
3
  • 9
    I would check if malloc returned NULL ;) Nov 27, 2011 at 16:41
  • @KerrekSB, what should I pass to the intdup function. The first parameter is the variable to be copied, and the second? Dec 24, 2015 at 9:19
  • @Identicon: Not quite; The first parameter is a pointer to the first element in your existing array of integers, and the second parameter is the number of elements that you want to copy (i.e. the size of the array or less). The first argument you pass needn't be a variable, it could also be some non-trivial expression, for example: int a[100]={/*...*}; int * p = intdup(a + 25, 13);
    – Kerrek SB
    Dec 24, 2015 at 10:23
2

This could work, if used properly:

#define arrayDup(DST,SRC,LEN) \
            { size_t TMPSZ = sizeof(*(SRC)) * (LEN); \
              if ( ((DST) = malloc(TMPSZ)) != NULL ) \
                memcpy((DST), (SRC), TMPSZ); }

Then you can do:

double dsrc[4] = { 1.1, 2.2, 3.3, 4.4 };
int *isrc = malloc(3*sizeof(int));
char *cdest;
int *idest;
double *ddest;
isrc[0] = 2; isrc[1] = 4; isrc[2] = 6;

arrayDup(cdest,"Hello",6); /* duplicate a string literal */
arrayDup(idest,isrc,3);    /* duplicate a malloc'ed array */
arrayDup(ddest,dsrc,4);    /* duplicate a regular array */

The caveats are:

  • the SRC and DST macro parameters are evaluated more than once
  • The type of the pointer/array passed as SRC must match that of the source array (no void * unless cast to the correct type)

On the other hand, it works whether the source array was malloc()ed or not, and for any type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.