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