Search code examples
carrayssplitmemcpy

How to split array into two arrays in C


Say i have an array in C

int array[6] = {1,2,3,4,5,6}

how could I split this into

{1,2,3}

and

{4,5,6}

Would this be possible using memcpy?

Thank You,

nonono


Solution

  • Sure. The straightforward solution is to allocate two new arrays using malloc and then using memcpy to copy the data into the two arrays.

    int array[6] = {1,2,3,4,5,6}
    int *firstHalf = malloc(3 * sizeof(int));
    if (!firstHalf) {
      /* handle error */
    }
    
    int *secondHalf = malloc(3 * sizeof(int));
    if (!secondHalf) {
      /* handle error */
    }
    
    memcpy(firstHalf, array, 3 * sizeof(int));
    memcpy(secondHalf, array + 3, 3 * sizeof(int));
    

    However, in case the original array exists long enough, you might not even need to do that. You could just 'split' the array into two new arrays by using pointers into the original array:

    int array[6] = {1,2,3,4,5,6}
    int *firstHalf = array;
    int *secondHalf = array + 3;