首页 > 解决方案 > 访问内存以遍历数组内联

问题描述

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

    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++ 的理解:)

标签: c++

解决方案


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

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


推荐阅读