繁体   English   中英

如何使用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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM