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()?
2 Answers
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 Comments
Roman Byshko
I would check if malloc returned NULL ;)
Box Box Box Box
@KerrekSB, what should I pass to the
intdup function. The first parameter is the variable to be copied, and the second?Kerrek SB
@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);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
SRCandDSTmacro parameters are evaluated more than once - The type of the pointer/array passed as
SRCmust match that of the source array (novoid *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.
strduprelies on a null terminator, which int arrays don't have. What's wrong withmemcpy?memcpyas KSB suggested below.