C++ memcpy with Arrays of Structures
In C++, you can use the memcpy function to copy an array of structs. Here is an example code:
#include <iostream>
#include <cstring>
struct MyStruct {
int id;
char name[20];
};
int main() {
MyStruct arr1[3] = {{1, "Alice"}, {2, "Bob"}, {3, "Charlie"}};
MyStruct arr2[3];
// 使用memcpy复制结构体数组
memcpy(arr2, arr1, sizeof(arr1));
// 打印复制后的数组
for (int i = 0; i < 3; i++) {
std::cout << "id: " << arr2[i].id << ", name: " << arr2[i].name << std::endl;
}
return 0;
}
In the example above, we defined a struct MyStruct with id and name members, then created two struct arrays arr1 and arr2. By using the memcpy function, we copied the data from arr1 to arr2, and printed the copied result.