griffin175
griffin175

Reputation: 131

Swapping elements in an array of structs using pointers c++

I see a couple similar questions but they don't have answers for my specific case. I simply need to swap the location of two elements in an array of structs, but everything I've tried so far will only copy one or the other. I believe the issue lies in the swap function.

I need do do this without the use of standard library functions. Here's what I have:

struct RentalCar {
    int year;
    char make[STRLEN];
    char model[STRLEN];
    float price;
    bool available;
};

void carCopy(RentalCar *dest, RentalCar *source) { // dest = source
    dest->year = source->year;
    myStrCpy(dest->make, source->make);            // copy c-strings
    myStrCpy(dest->model, source->model);
    dest->price = source->price;
    dest->available = source->available;
}

void carSwap(RentalCar *car1, RentalCar *car2) {
    RentalCar *carTemp = car1;
    carCopy(carTemp, car2);   // tried different orders, only copy no swap
    carCopy(car2, car1);
}

char *myStrCpy(char *dest, const char *source) {    // copy cstring
    char *origin = dest;                            // non iterated address
    while (*source || *dest) {
        *dest = *source;
        dest++;
        source++;
    }
    return origin;  // could return void instead
}

Upvotes: 0

Views: 682

Answers (2)

Elliott
Elliott

Reputation: 2623

You're mixing shallow copies with deep copies:

void carSwap(RentalCar *car1, RentalCar *car2) {
    RentalCar *carTemp = car1; // shallow copy
    carCopy(carTemp, car2);   // deep copy: overrides carTemp AND car1
    carCopy(car2, car1); // car1 and car2 already have the same values
    // original car1 data is lost
}

Because carSwap is given RentalCar* (and not RentalCar**) we can't change the user's pointer, so we must stick to deep copies.

We could do this (and still use the other functions):

void carSwap(RentalCar *car1, RentalCar *car2) {
    RentalCar carTemp = *car1;
    carCopy(car1, car2);
    carCopy(car2, &carTemp);
}

But we don't need the other functions. We can just do this:

void carSwap(RentalCar *car1, RentalCar *car2) {
    RentalCar carTemp = *car1;
    *car1 = *car2;
    *car2 = carTemp;
}

Upvotes: 1

Harry Braviner
Harry Braviner

Reputation: 667

In carSwap, carTemp is a pointer pointing to the same memory location as car1. The line

carCopy(carTemp, car2);   // tried different orders, only copy no swap

overwrites car1 with car2.

Change carSwap to this:

void carSwap(RentalCar *car1, RentalCar *car2) {
    RentalCar carTemp;
    carCopy(&carTemp, car2);
    carCopy(car2, car1);
    carCopy(car1, &carTemp);
}

Upvotes: 1

Related Questions