c++ - 访问内存以内联遍历数组

标签 c++

我想通过遍历数组的内存位置来访问数组中的元素。由于任何给定数组的元素都是按顺序存储的,因此我使用 ++ 运算符递增它们的内存位置。 我可以写一些这样的代码:

    int someArray[4];
    someArray[0] = 44;
    someArray[1] = 55;
    someArray[2] = 66;
    someArray[3] = 77;

    int *location = someArray;
    cout << *++location << endl; // OUTPUT: 55
    cout << *++location << endl; // OUTPUT: 66

但是,当我尝试以下任一操作时收到错误消息:

    cout << *(++someArray) << endl;
    // error: lvalue required as increment operand cout << *(++someArray) << endl;

    // OR

    cout << *++&someArray << endl;
    // error: lvalue required as increment operand cout << *++&someArray << endl;

    // OR

    cout << *++(&someArray) << endl;
    // error: lvalue required as increment operand cout << *++(&someArray) << endl;

我是 c++ 的新手,但据我了解,在变量前加上 & 前缀会检索其内存位置。 然而,数组将在没有 & 的情况下返回它们的内存位置。 无论我是否使用 & 我都会收到错误。 我想在线递增数组,但是我必须声明一个变量,其中首先存储位置。

我希望在这里能澄清我对 C++ 的理解 :)

最佳答案

你最后三行的问题是你试图增加一个常量。

someArray 的地址是一个常量。你无法改变它。您必须先将其分配给指针变量,然后才能更改指针。

关于c++ - 访问内存以内联遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56564452/

相关文章:

c++ - 在我的 C++ 程序中构建错误

c++ - 如何在不丢失原始调用堆栈的情况下重新抛出异常?

c++ - 没有元素满足谓词时的 is_partitioned 行为

c++ - 删除数组

c++ - 在cuda中使用静态成员函数模板结构的替代方法?

c++ - 使用-static-libstdc++ 构建应用程序和共享库时出现段错误

c++ - 使用 libavformat 不播放的 H.264 混合到 MP4

c++ - 为什么 bada 不需要 scoped_ptr?

c++ - 程序可以在调用 kill 函数之前返回/终止吗?

c++ - 如何定义多个源文件访问的linux内核变量?