0

I'm given a struct:

struct Agency {
    char name[255];
    int zip[5];
    RentalCar inventory[5];     // array of RentalCar objects
};

I need to retrieve data from a file to fill an array of 3 Agency objects. To set the values for the first item in the inventory array is easy,

Agency ag[3];
for (int i = 0; i < 3; i++) {
ag->inventory->setWhatever();
ag++;     // easy to iterate through this array
}

But It's not that easy to iterate through the inventory array within the agency array.

inventory++;        // doesn't know what object this is associated with
ag->inventory++;    // also doesn't work
4
  • Do you know how to read one RentalCar from the file? Commented Jun 14, 2018 at 22:59
  • Can you not do ag[0].inventory[1] for example to access the second RentalCar from the first Agency? Would it be ok or do you need to do this through pointers? Commented Jun 14, 2018 at 23:01
  • Anyway, there you go Commented Jun 14, 2018 at 23:06
  • @Beta yes, and I can write over the first one in the array as many times as I want, I just can't get to the second or anything passed that. Commented Jun 14, 2018 at 23:44

1 Answer 1

2
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++;
}

Arrays can be accessed through index, for example ag[0] ag[1] ag[2] but this is illegal: ag++. The array name ag decays to pointer to first element when used alone, but it is not a pointer.

Pointers, on the other hand can scroll memory address with + and - operations. Be wary, because they could easily point to memory not reserved for your program.

Sign up to request clarification or add additional context in comments.

3 Comments

I can't use the array index operator [ ], only for declaring array. I know it's stupid but that's what's required. But if I were able to use ptr->inventory[1]->setWhatever(); wouldn't it be ptr->inventory[1].setWhatever(); since inventory[1] is a variable not a pointer?
@griffin175 Agency *ptr = &ag[0]; and Agency *ptr = ag; result in the same thing. That should eliminate all of the []s used to index.
@user4581301 Sure thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.