简体   繁体   中英

How can I concatenate two arrays in C using memcpy?

I have 2 arrays with coordinates and i want to copy them into one array. I used 2 for loops and its working, but i want to know, if i could do it without them, i dont know how to use memcpy in this situation. Here is my code:

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;
}

Just calculate the correct number of bytes to copy and copy from each origin to the correct offset:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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