Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best method to create a sub array from an array in C

Tags:

arrays

c

I have an array say a[3]={1,2,5} . I have to create another array a2[2]={2,5}.

What I have tried is to just create a new array a2[] and just copy all the elements from the required position range.

Is there any other method to accomplish this in C?.

like image 662
poorvank Avatar asked Jul 20 '13 14:07

poorvank


People also ask

How do you create a sub array from an array?

Use the copyOfRange() to Create a Subarray From an Array in Java. Java provides us with a way to copy the elements of the array into another array. We can use the copyOfRange() method, which takes the primary array, a starting index, and an ending index as the parameters and copies that subarray to the destined array.


2 Answers

memcpy(a2, &a[1], 2*sizeof(*a));
like image 184
BLUEPIXY Avatar answered Oct 19 '22 10:10

BLUEPIXY


Instead of having a second array, just use a pointer:

int a[3]={1,2,5};
int *p = &a[1];

If they have to be distinct, you have no choice other than to copy the array elements into a new array.

like image 38
ouah Avatar answered Oct 19 '22 10:10

ouah