如何使用指针遍历结构数组中的数组

How can I iterate through an array within an array of a struct using pointers

本文关键字:数组 结构 遍历 何使用 指针      更新时间:2023-10-16

我得到了一个结构:

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单独使用时衰减为指向第一个元素的指针,但它不是指针。

另一方面,指针可以使用 + 和 - 操作滚动内存地址。要小心,因为它们很容易指向未为您的程序保留的内存。