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()?
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:
SRC and DST macro parameters are evaluated more than onceSRC 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.