c++ - 在 C++ 中使用指针引用替换数组元素

标签 c++

我想通过引用用其他值替换数组元素。但是我在这样做时遇到了问题。我的代码如下。在下面的代码中,我只得到最后一个值,即通过引用传递后的 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/

相关文章:

c++ - 使用 qmake 和 MSVC2015 创建共享库(.lib 和 .dll)

c++ - 为什么没有用于引用数组的 std::string 构造函数?

c++ - Ffmpeg header 不在 Windows 中编译

c++ - 手写 Action

c++ - "A::B::C v;"是否意味着 A 和 B 是命名空间而 C 是一个类?

c++ - 如何在 C++ 中使函数内联

c++ - 嵌套类中的 "Invalid covariant return type"错误,其方法返回基于模板的对象

c++ - 一个数字,因为它是质数部分

c++ - 使用宏时错误枚举没有成员

c++ - 与位置无关的代码和 vtable