Which loop snippet correctly copies n elements from src to dest?

Enhance your programming skills with the RECF Programming Test. Features flashcards and multiple choice questions with hints and explanations. Prepare for success!

Multiple Choice

Which loop snippet correctly copies n elements from src to dest?

Explanation:
When copying n elements, you need to touch exactly those indices from 0 up to n-1 and assign each source element to the corresponding destination element. The loop that does dest[i] = src[i] with i starting at 0 and continuing while i < n achieves this, copying every element in order without going past the end. The other approaches break that idea in different ways. Using i <= n would try to access index n, which is outside the n-element range, leading to undefined behavior. Assigning dest = src just changes the pointers so both refer to the same memory instead of copying values. Using memcpy with a count of n copies n bytes, not n elements, so unless each element is exactly one byte, this won’t copy the intended data.

When copying n elements, you need to touch exactly those indices from 0 up to n-1 and assign each source element to the corresponding destination element. The loop that does dest[i] = src[i] with i starting at 0 and continuing while i < n achieves this, copying every element in order without going past the end.

The other approaches break that idea in different ways. Using i <= n would try to access index n, which is outside the n-element range, leading to undefined behavior. Assigning dest = src just changes the pointers so both refer to the same memory instead of copying values. Using memcpy with a count of n copies n bytes, not n elements, so unless each element is exactly one byte, this won’t copy the intended data.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy