将一个数组分配给另一个数组 C++ [英] Assigning one array to another array c++
本文介绍了将一个数组分配给另一个数组 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好,我是 C++ 的初学者,谁能给我解释一下
Hello I am beginner in c++ , can someone explain to me this
char a[]="Hello";
char b[]=a; // is not legal
然而,
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);
推荐答案
它不是复制数组;它把它变成了一个指针.如果你修改它,你会亲眼看到:
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
如果需要复制数组,使用std::copy
:
If you need to copy an array, use std::copy
:
int a1[] = {1,2,3};
int a2[3];
std::copy(std::begin(a1), std::end(a1), std::begin(a2));
如果您发现自己这样做,您可能需要使用 std::array
.
If you find yourself doing that, you might want to use an std::array
.
这篇关于将一个数组分配给另一个数组 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文