【发布时间】:2016-09-17 07:14:35
【问题描述】:
请参考下面的代码(和 cmets)。
我正在尝试使数组 = newArray。
在 C++ 中执行此操作的正确语法是什么?
我正在尝试将 array 指向与 中的 newArray 相同的内存位置>memoryCopy(),
从而将 newArray 复制到 array 中,而不必像在 deepCopy 中那样逐个元素地进行()
#include <iostream>
using namespace std;
void deepCopy(int array[], int size);
void memoryCopy(int *array, int size);
void show(int array[], int size);
int main ()
{
int array[] = {1,1,1};
show(array,3); // shows array [] = {1,1,1}
deepCopy(array, 3);
show(array,3); // shows array [] = {0,0,0}
memoryCopy(array, 3);
show(array,3); // shows array [] = {5,0,0}
// I need the above to show {5, 5, 5} ^ ^
// How can I do this in memoryCopy() using pointers?
}
void memoryCopy(int *array, int size)
{
int newArray[] = {5,5,5};
// I need to make array = newArray ...
// ... but without copying it over element by element
memcpy(array,newArray, 3); // <--???
}
void deepCopy(int array[], int size)
{
int newArray [] = {0,0,0};
for (int i = 0; i < size; i++)
array[i] = newArray[i];
}
void show(int array[], int size)
{
int i;
cout << "array [] = {";
for (i = 0; i < size-1; i++)
cout << array[i] << ",";
cout << array[i] << "}" << endl;
}
【问题讨论】:
-
使用
std::copy()。 -
怎么样?我需要的是执行此操作的语法示例。
-
你能和
memcpy(array,newArray, 3*sizeof(int));核实一下吗? -
如果您使用 std::vector 或其他 STL 容器,您可以编写 new=old 并且它会进行复制。
-
@nulldreamer Here's the reference with examples
标签: c++ arrays function pointers copy