将新数组分配给参考变量
void byReference(int (&p)[3]){
int q[3] = {8, 9, 10};
p = q;
}
我想编写功能,可以在其中重新分配新数组的P。我不确定我们是否可以做到这一点。
我的目标: 我想更改原始数组,就像我们通过呼叫引用进行两个数字交换一样。
Edit:
my working solution :
void byReference(int*& p){
int* q = new int[2];
q[0] = 8;
q[1] = 9;
p = q;
}
int main(){
int *x = new int[2];
x[0] = 1;
x[1] = 2;
byReference(x);
return 0;
}
void byReference(int (&p)[3]){
int q[3] = {8, 9, 10};
p = q;
}
I want to write function where i can reassign the p with new array. I am not sure if we can do that.
My goal :
i want to change the original array, like we do swapping of two number by call-by reference.
Edit:
my working solution :
void byReference(int*& p){
int* q = new int[2];
q[0] = 8;
q[1] = 9;
p = q;
}
int main(){
int *x = new int[2];
x[0] = 1;
x[1] = 2;
byReference(x);
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在C ++中,建议使用
std :: Array
用于固定大小数组,而std :: vector
用于动态大小数组。它们俩都可以通过引用传递,以通过函数修改。
这要求的函数声明该参数是使用
&
符号通过Refernce 传递的。请参见下面的示例:
In c++ it is recomended to use
std::array
for fixed size arrays, andstd::vector
for a dynamic size arrays.Both of them can be passed by refernce, to be modified by a function.
This requires the function to declare that the argument is passed by refernce using the
&
symbol.See the example below:
您不能通过分配复制数组。您可以使用std ::复制
...。
You cannot copy arrays by assignment. You can use std::copy
....
您可以这样做:
输出:
You can do it like this:
Output: