28

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? Commented 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(). Commented 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]; ?? Commented Nov 27, 2011 at 16:42
  • @Chris: I got the point I have to write my own using memcpy as KSB suggested below. Commented Nov 27, 2011 at 16:44
  • @EvilTeach: I used malloc. I mean I would. Commented Nov 27, 2011 at 16:45

2 Answers 2

40

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I would check if malloc returned NULL ;)
@KerrekSB, what should I pass to the intdup function. The first parameter is the variable to be copied, and the second?
@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);
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.