How to split array into two arrays in C

123hal321 picture 123hal321 · May 1, 2011 · Viewed 57.6k times · Source

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

Answer

Frerich Raabe picture Frerich Raabe · May 1, 2011

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;