0

I have an array A [8] = {0}; And another array B[20] = {0};

I want to move all the values from B[12...20] to A[0...8]. How can i exactly change the indices? is there a formula? So B[12] -->A[0] B[13] -->A[1]

Thank you.

1
  • Note that B[20] is out of bounds. You probably mean B[12...19]. Commented Aug 8, 2013 at 11:10

4 Answers 4

7

Use std::copy. It works for user defined types too:

std::copy(B+12, B+20, A);

or, in c++11,

std::copy(std::next(B,12), std::end(B), std::begin(A));
Sign up to request clarification or add additional context in comments.

Comments

6

You should use std::copy here, which will work correctly no matter the type of elements in your arrays (speaking of which, you don't show that type -- the question has invalid syntax).

std::copy(B + 12, B + 20, A);

Comments

2

Simply write a loop

int offset = 12;
int lenA = 8;

for(int i=0; i < lenA; i++) {
   A[i] = B[i+offset];
}

Comments

1

memcpy(A, B + 12, 8 * sizeof(A[0])); should do the trick.

Assuming A and B are both the same type.

6 Comments

hi @dunc is there a way to do it using for loop?
It won't copy memcpy would copy number of bytes. If it is an integer or some other object - byte count would differ
I'd actually recommend the std::copy answer from Jon, since you are using C++.
I actually wanted to see how I can switch between the incides using the for loop
This will only work if the arrays are of basic C compatible types. Use std::copy, it is safer, it indicated the intent better (you are copying elements, NOT memory), and very likely compiles down to a memcpy where is't safe to do so anyway
|

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.