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
是一个常数。你不能改变它。您必须先将其分配给指针变量,然后才能更改指针。
推荐阅读
- android - 可以忽略 ReactNative 中渲染的导航和 screenProps 更新吗?
- database - 如何用数据库中的数据填充数组
- c# - C# DataGridView 多重过滤器
- javascript - How to change dropdown arrow image with javascript
- latex - 试图在 LaTex 中使表格居中
- python - 查找特定标签 Python BeautifulSoup
- uno-platform - 使用 Uno Platform 在类库中获取设备信息
- google-fit - Google Fit 估计通过 REST API 的步数会随着一些用户的时间减少
- xml - CakePhp 如何将 http 响应(以 xml 格式)保存到服务器?
- types - 为什么 rustc 说推断的类型不匹配?