将一个数组分配给另一个数组 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23850656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Assigning one array to another array c++
提问by Bala
Hello I am beginner in c++ , can someone explain to me this
你好,我是 C++ 的初学者,有人可以向我解释这个吗
char a[]="Hello";
char b[]=a; // is not legal
whereas,
然而,
char a[]="Hello";
char* b=a; // is legal
If a array cannot be copied or assigned to another array , why is it so that it is possible to be passed as a parameter , where a copy of the value passed is always made in the method
如果一个数组不能被复制或分配给另一个数组,为什么它可以作为参数传递,其中传递的值的副本总是在方法中进行
void copy(char[] a){....}
char[] a="Hello";
copy(a);
回答by kirbyfan64sos
It isn't copying the array; it's turning it to a pointer. If you modify it, you'll see for yourself:
它不是复制数组;它把它变成了一个指针。如果你修改它,你会亲眼看到:
void f(int x[]) { x[0]=7; }
...
int tst[] = {1,2,3};
f(tst); // tst[0] now equals 7
If you need to copy an array, use std::copy
:
如果需要复制数组,请使用std::copy
:
int a1[] = {1,2,3};
int a2[3];
std::copy(std::begin(a1), std::end(a1), std::begin(a2));
If you find yourself doing that, you might want to use an std::array
.
如果您发现自己这样做,您可能需要使用std::array
.
回答by vsoftco
The array is silently (implicitly) converted to a pointer in the function declaration, and the pointer is copied. Of course the copied pointer points to the same location as the original, so you can modify the data in the original array via the copied pointer in your function.
在函数声明中,数组被悄悄地(隐式地)转换为指针,并复制指针。当然,复制的指针指向的位置与原始指针相同,因此您可以通过函数中的复制指针来修改原始数组中的数据。