FourOfAKind
FourOfAKind

Reputation: 2418

How to copy one integer array to another

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()?

Upvotes: 27

Views: 87446

Answers (2)

Dmitri
Dmitri

Reputation: 9375

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.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 476950

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

Upvotes: 38

Related Questions