C++ Assign an array to another array
Looping traversal assignment
Use a loop structure (such as for loops) to perform assignment copying elements.
Here is the sample code:
#include <iostream> const int SIZE = 5; // The size of the array int main() { int arr1[SIZE] = {1, 2, 3, 4, 5}; // Original array int arr2[SIZE]; // Target array // Assign the value of arr1 to arr2 for (int i = 0; i < SIZE; ++i) { arr2[i] = arr1[i]; } // Print the value of arr2 for (int i = 0; i < SIZE; ++i) { std::cout << arr2[i] << " "; } std::cout << std::endl; return 0; }
In the above code, two arrays are definedarr1
andarr2
and use a loop structure toarr1
Assign the values to eacharr2
. Then we use another loop to printarr2
value.
Run the above code and the output will be:
1 2 3 4 5
This showsarr2
Successfully fromarr1
The same value was received.
Use the functions std::copy or std::memcpy in the standard library
In C++, use the assignment operator directly=
It is possible to implement the address assignment of one array to another array. However, the contents of the array are not copied. This will cause two arrays to share the same memory space, and modifications to one array will also affect the other.
If you want to implement the overall assignment of array content, you can use the functions in the standard librarystd::copy
orstd::memcpy
, at this time, there are two arrays (that is, the addresses are different).
Here is the sample code:
#include <iostream> #include <algorithm> #include <cstring> const int SIZE = 5; // The size of the array int main() { int arr1[SIZE] = {1, 2, 3, 4, 5}; // Original array int arr2[SIZE]; // Target array // Use std::copy for overall assignment std::copy(arr1, arr1 + SIZE, arr2); // Print the value of arr2 for (int i = 0; i < SIZE; ++i) { std::cout << arr2[i] << " "; } std::cout << std::endl; return 0; }
In the above code, usestd::copy
The function willarr1
Copy the content toarr2
middle. so,arr1
andarr2
There will be independent memory space, and modifications to one array will not affect another array.
Run the above code and the output will be:
1 2 3 4 5
This showsarr2
Successfully fromarr1
The same value is received in the two arrays.
Using standard library containers
If you use standard library containers (such as std::vector, std::array, etc.) in C++, you can directly use the container's assignment operator or copy constructor to copy between arrays.
#include <vector> std::vector<int> source = {1, 2, 3, 4, 5}; std::vector<int> destination = source;
This approach is suitable for use with standard library containers, which provide convenient copy operations.
Regardless of the method you choose, make sure that the target array is large enough to accommodate elements of the source array, and be careful to avoid out-of-bounds access of the array.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.