我正在学习指针,但我无法让这段代码工作。这是我到目前为止所拥有的:
void incrementArray(int* a[]) {
for(auto& x : a) {
++x;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int array[] = {0,1,2,3,4,5,6,7,8,9};
for(auto x : array) {
cout << x << '\n';
}
incrementArray(&array);
for(auto x : array) {
cout << x << '\n';
}
}
我收到以下错误:
'incrementArray' : cannot convert parameter 1 from 'int (*)[10]' to 'int *[]'
我该怎么做才能修复我的代码?
最佳答案
C 风格数组的语法很有趣。要将数组传递给函数,请使用 int a[]
这不会复制数组,函数内部对数组的更改将修改外部数组。你只需要调用 incrementArray(array);
no & needed
您可以尝试使用遵循更正常语法的 std::array
类。
关于c++ - 通过函数修改数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24346914/