void byReference(int (&p)[3]){
int q[3] = {8, 9, 10};
p = q;
}我想编写函数,在那里我可以用新数组重新分配p。我不确定我们是否能做到。
我的目标:我想改变原来的数组,就像我们通过调用通过引用交换两个数字一样。
编辑:
我的工作解决方案:
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;
}发布于 2022-05-07 15:38:53
不能通过赋值复制数组。您可以使用std::copy
void byReference(int(&p)[3]) {
int q[3] = { 8, 9, 10 };
// p = q;
std::copy(&q[0], &q[3], &p[0]);
}……
int a[3] = { 1, 2, 3 };
byReference(a);
// a now 8,9,10https://stackoverflow.com/questions/72153819
复制相似问题