How to copy one integer array to another

前端 未结 2 1080
轮回少年
轮回少年 2020-12-14 08:43

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条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 09:26

    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.

提交回复
热议问题