![]() |
VOOZH | about |
In this article, we will learn how to copy all the elements of one array to another array in C.
The simplest method to copy an array is by using the memcpy() function. Let's take a look at an example:
1 2 3 4 5
Explanation: The memcpy() function copied the whole block of arr1 memory to arr2.
This method operators directly on low level memory so it is fast but there are some chances of error if not properly used.
There is also a few more methods to copy all the elements of one array to another. Some of them are as follows:
Table of Content
This method uses a loop to iterate through the array and assign each element to the corresponding index of another array.
1 2 3 4 5
This method provides more control of the copying process.
In this method, only one element is copied in one function call. The rest of the elements are then copied by recursively calling the function for next elements.
1 2 3 4 5
This method is generally not preferred because it may take more memory as compared to other methods (if tail call optimization is not done).
This method is similar to the loop method but here, pointers are used instead of array names.
1 2 3 4 5