30

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?.

2 Answers 2

36
memcpy(a2, &a[1], 2*sizeof(*a));
Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't it be memcpy(&a2, &a[1], 2*sizeof(*a)); ?
No, a2 is already a pointer to array but a[i] is number instead.
28

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.