我想通过引用用其他值替换数组元素。但是我在这样做时遇到了问题。我的代码如下。在下面的代码中,我只得到最后一个值,即通过引用传递后的 10。但我想获得更改后的值,如 6、7、8、9、10。请建议:
#include <iostream>
using namespace std;
int temp=6;
int byreference (int *x){
for (int t=0;t<5;t++){
*x=temp+t;
}
}
int main ()
{
int array[5];
for (int s=0;s<5;s++){
array[s]=s+1;
byreference(&array[s]);
cout<<*&array[s]<<endl;
}
}
最佳答案
没有 vector :
#include <iostream>
using namespace std;
int temp=6;
int byreference (int *x){
for (int t=0;t<5;t++){
*(x+t)=temp+t;
}
}
int main ()
{
int array[5];
for (int s=0;s<5;s++){
array[s]=s+1;
byreference (array);
cout<<array[s]<<endl;
}
}
输出:
6
7
8
9
10
关于c++ - 在 C++ 中使用指针引用替换数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24278081/