如何使用 memcpy 在 C 中连接两个数组?

How can I concatenate two arrays in C using memcpy?

我有 2 个带坐标的数组,我想将它们复制到一个数组中。我使用了 2 个 for 循环及其工作原理,但我想知道,如果没有它们我也能做到,我不知道在这种情况下如何使用 memcpy。这是我的代码:

int *join(int *first, int *second,int num, int size) {

int *path= NULL;
int i = 0 , j = 0;

path = (int*) malloc (2*size*sizeof(int)); 

    for(i = 0 ; i < num; i++) {
        path[i * 2] = first[i * 2];
        path[i * 2 + 1] = first[i * 2 + 1];

    }

    for(i = num; i < size ; i++) { 
        path[(i*2)] = second[(j+1)*2];
        path[(i*2)+1] = second[(j+1)*2 +1];
        j++;
    }
  return path;
}

只需计算要复制的正确字节数并从每个源复制到正确的偏移量即可:

int *join(int *first, int *second, int num, int size) {
    // Compute bytes of first
    const size_t sizeof_first = sizeof(*first) * 2U * num;
    // Computes bytes of second as total size minus bytes of first
    const size_t sizeof_second = sizeof(int) * 2U * size - sizeof_first;

    int *path = malloc(sizeof(int) * 2U * size); 

    // Copy bytes of first
    memcpy(path, first, sizeof_first);
    // Copy bytes of second immediately following bytes of first
    memcpy(&path[2U * num], second, sizeof_second);
    return path;
}