[英]Using memcpy with smart pointers in C++
I have a smart pointer defined like this我有一个这样定义的智能指针
auto ptr = make_shared<int[]>(5);
and another array和另一个数组
int arr[] = {1,2,3,4,5};
I want to copy data in arr to ptr, I tried using this我想将 arr 中的数据复制到 ptr,我尝试使用这个
memcpy(ptr.get(), arr, 5 * sizeof(int))
But when I try printing like this但是当我尝试像这样打印时
for (int i = 0; i < 5; i++) {
std::cout<<ptr[i]<<std::endl;
}
I get我明白了
malloc(): corrupted top size
Process finished with exit code 134
(interrupted by signal 6: SIGABRT)
Is there something wrong with the ptr initialization? ptr初始化有问题吗?
Here is an example of what you need (hope so):这是您需要的示例(希望如此):
#include <iostream>
#include <memory>
#include <cstring>
int main() {
// Create a unique_ptr to an int array
std::unique_ptr<int[]> arr1(new int[5]{ 1, 2, 3, 4, 5 });
// Create a unique_ptr to an int array
std::unique_ptr<int[]> arr2(new int[5]);
// Use memcpy to copy the data from arr1 to arr2
std::memcpy(arr2.get(), arr1.get(), 5 * sizeof(int));
// Print the contents of arr2
for (int i = 0; i < 5; i++) {
std::cout << arr2[i] << " ";
}
std::cout << std::endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.