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?.
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.
memcpy(a2, &a[1], 2*sizeof(*a));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With