Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 360
123hal321 Avatar asked May 01 '11 17:05

123hal321


1 Answers

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;
like image 139
Frerich Raabe Avatar answered Oct 22 '22 05:10

Frerich Raabe