如何使用指针遍历结构数组中的数组
How can I iterate through an array within an array of a struct using pointers
我得到了一个结构:
struct Agency {
char name[255];
int zip[5];
RentalCar inventory[5]; // array of RentalCar objects
};
我需要从文件中检索数据以填充 3 个 Agency 对象的数组。 为库存数组中的第一项设置值很容易,
Agency ag[3];
for (int i = 0; i < 3; i++) {
ag->inventory->setWhatever();
ag++; // easy to iterate through this array
}
但是,在代理数组中循环访问库存数组并不容易。
inventory++; // doesn't know what object this is associated with
ag->inventory++; // also doesn't work
Agency ag[3];
Agency *ag_ptr= &ag[0]; // or: Agency *ag_ptr = ag; //as this decays to pointer
for (int i = 0; i < 3; i++) {
Rentalcar *rental_ptr = ag_ptr->inventory; //rental_ptr now points at the first RentalCar
rental_ptr->setWhatever(); //set first rental car
rental_ptr++;
rental_ptr->setWhatever(); //set second rental car
ag_ptr++;
}
数组可以通过索引访问,例如ag[0] ag[1] ag[2]
但这是非法的:ag++
.数组名称ag
单独使用时衰减为指向第一个元素的指针,但它不是指针。
另一方面,指针可以使用 + 和 - 操作滚动内存地址。要小心,因为它们很容易指向未为您的程序保留的内存。
相关文章:
- 从函数中全局删除并重新实例化数组结构,而无需在编译时知道数组的大小
- 如何使用函数的输出初始化 const 数组结构字段?
- 传递数组结构、ofstream 和 interger 以运行
- 从文本文件中读取并输入到数组结构中,然后显示读取的数据C++
- 将文本文件读取到数组结构中
- C/C++中数组结构和数组结构的通用接口
- C++ MDC final-在字符类型的数组结构中按字母顺序对记录中的名称进行排序
- C++ 使用数组结构创建平衡的二叉搜索树
- C++:释放动态数组(结构成员)和指向此结构的指针的方法
- 使用 vector 在 c++ 中声明 3D 数组结构
- 数组结构无法正确打印
- 如何在C++中访问数组结构内部的数组结构
- CIN进入数组结构似乎什么也没输入
- ifstream将数组结构到txt文件中,然后尽可能将其提取为数组
- wlanapi-将WlanFreeMemory释放其WLAN_INTERFACE_INFO数组结构
- 显示数组结构 c++
- C++ 使用函数访问数组结构的方法是什么?
- 将庞大的数组结构复制到 GPU
- 如何封送包含字符矩阵的数组结构
- C++多维数组结构的对齐