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
}
carSwap()needs to create an actual object, not just a pointer. SincecarTemppoints atcar1, the function is equivalent tocarCopy(car1, car2); carCopy(car2, car1);whih has the net effect of setting the contents ofcar1andcar2to the original values ofcar2. To fix, create an object not a pointer, then do three copies (e.g.car1to thecarTemp,car2tocar1, thencarTemptocar2).