c++ - 通过函数修改数组元素

标签 c++ visual-c++

我正在学习指针,但我无法让这段代码工作。这是我到目前为止所拥有的:

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/

相关文章:

c++ - 数组内的自增运算符

c++ - 单线程可以双重锁定互斥量吗?

c++ - 初始化包含固定大小数组的 C++ 结构体

c++ - 带有 ITK 和 FFTW 的 VS2008 中的错误 LNK2019(未解析的外部符号)

c++ - static constexpr char m_pszFoo[] = "***FOO***"有编译错误表达式没有计算常量

c++ - OpenGL:如何获取 GPU 使用百分比?

c++ - 将 Visual C++ 控制台输出复制(不重定向)到文本文件,同时仍在控制台窗口中查看输出

.net - C++/CLI : inherit from one CLR class, 多个 C++ 类

c++ - 启动服务器时出现 std::exception (WinSock2)

c++ - 反转十六进制值的数字