当我们在C ++中的参数中传递它们时,如何修改某些数组而不修改其他数组?

时间:2017-04-05 15:58:44

标签: c++ arrays

我有以下C ++代码。我可以修改数组x []的内容,因为我们将它传递给函数modify但是我不想在我们传递它时修改数组z的内容。我尝试这样做时遇到了一些错误。请问你能帮帮我吗? 似乎我在函数中初始化矩阵m时也有错误。

#include<iostream>
using namespace std;
void modify(int y[], int f[], const int size)
{
    int m[size];
    for (int i = 0; i < size; i++)
    {
        m[i] = f[i];
    }
    for (int i = 0; i <= 5; i++)
    {
        y[i] = 2 * y[i];
        m[i] = 2 * m[i];
        cout << "y[" << i << "]=" << y[i] << "\t"<<endl;
        cout << "m[" << i << "]=" << m[i] << "\t"<<endl;
    }
    cout << endl;
}
int main(){
    int x[6] = {1,2,3,4,5,6};
    int z[6] = {1,2,3,4,5,6};
    for (int i = 0; i <= 5; i++)
    {   cout << "x[" << i << "]=" << x[i]<<"\t"<<endl;
        cout << "z[" << i << "]=" << z[i] << "\t"<<endl;
    }
    cout << endl;
    modify(x,z,6);
    for (int i = 0; i <= 5; i++)
    {
        cout << "x[" << i << "]=" << x[i] << "\t" << endl;
        cout << "z[" << i << "]=" << z[i] << "\t" << endl;
    }
    cout << endl;
    system("pause");
    return 0;
}

3 个答案:

答案 0 :(得分:4)

f的{​​{1}}参数设为modify数组。这样,就不能对const int的内容进行修改。

f

答案 1 :(得分:1)

在c ++中,您可以使用const关键字指定不得更改某些内容。

语句void modify(int y[], const int f[], const int size)表示函数不会更改f,因此您可以提供const参数。尝试通过f修改对象将产生编译错误。

声明const int z[6] = {1,2,3,4,5,6};表示不得更改z。如果您不小心尝试修改z或在可能发生更改的上下文中使用它,编译器将产生编译错误。

答案 2 :(得分:1)

谢谢大家的帮助。这是修复后的最终代码。我不想改变z但不使用const。

#include<iostream>
#include <vector>
using namespace std;

void modify(int [], int [], int);

int main()
{

int x[6] = {1,2,3,4,5,6};
int z[6] = {1,2,3,4,5,6};
for (int i = 0; i <= 5; i++)
{
    cout << "x[" << i << "]=" << x[i]<<"\t"<<endl;
    cout << "z[" << i << "]=" << z[i] << "\t"<<endl;
}
cout << endl;
modify(x,z,6);
for (int i = 0; i <= 5; i++)
{
    cout << "x[" << i << "]=" << x[i] << "\t" << endl;
    cout << "z[" << i << "]=" << z[i] << "\t" << endl;
}
cout << endl;
system("pause");
return 0;
}

void modify(int y[], int f[], int size)   
{
vector<int> m;
for (int i = 0; i < size; i++)
{
    m.push_back(f[i]);
}
for (int i = 0; i <= 5; i++)
{
    y[i] = 2 * y[i];
    m[i] = 2 * m[i];
    cout << "y[" << i << "]=" << y[i] << "\t"<<endl;
    cout << "m[" << i << "]=" << m[i] << "\t"<<endl;
}
cout << endl;
}