我得到了一个结构:
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
}
但是在 agency 数组中遍历 inventory 数组并不是那么容易。
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
单独使用时会衰减为指向第一个元素的指针,但它不是指针。
另一方面,指针可以通过 + 和 - 操作滚动内存地址。请小心,因为它们很容易指向未为您的程序保留的内存。
关于c++ - 如何使用指针遍历结构数组中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50867016/