例如,当你输入第十个元素并尝试改变它的值时,它会改变第三个元素,当你尝试改变第一个元素时,它可以改变第四个,某种随机出来,有什么问题?
int &change(int i);
int vals[10];
int main(){
int ch, newval;
cout << "Enter your array.." << endl;
for(int j = 0;j<10; j++) cin >> vals[j];
cout << "\n" <<"Choose element which you want to change.. ";
cin >> ch;
cout << "Enter the new value for this element.. ";
cin >> newval;
newval = change(vals[ch-1]);
cout << endl;
for (int i=0; i<10; i++) cout << vals[i] <<" "; // вывод массива
return 0;
}
int &change(int k){
return vals[k];
}
将元素索引传递给函数,而不是数组中的值: