Say I have this struct:
struct MyStruct {
int iID;
int iMyNumber;
};
Then I define an array of MyStructs:
struct MyStruct msTest[3];
I'm doing a sorting operation on a struct similar to this one by looking at the ID. Now, as soon as I find out which records should be swapped to sort the array I have to do the actual swapping. I tried this:
if (iSmallest != iCntr) {
stPTmp = &stXDB[iCntr];
&stXDB[iCntr] = &stXDB[iSmallest];
&stXDB[iSmallest] = &stPTmp;
}
stPTmp is defined as void *stPTmp; and iCntr and iSmallest contain the indices of the records to be swapped. My code doesn't work, but how do I fix it?
You need to swap elements, not pointers,
struct MyStruct stTmp;
if (iSmallest != iCntr) {
stTmp = stXDB[iCntr];
stXDB[iCntr] = stXDB[iSmallest];
stXDB[iSmallest] = stTmp;
}
Not terribly efficient, but your structs are small, so its only a bit more expensive than swapping pointers.
You could just let someone else think about this, i.e. use qsort():
#include <stdlib.h>
int compare_struct(const void *a, const void *b)
{
const struct MyStruct *sa = a, *sb = b;
return (sa->iID < sb->iID) ? -1 : sa->iId > sb->iId;
}
qsort(msTest, sizeof msTest / sizeof *msTest, sizeof *msTest, compare_struct);
Note that this totally removed the need to write the swapping function. Under the hood, this might be a bit more costly (could use malloc(), almost certainly uses memcpy()), but it's way easier to write and much easier to maintain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With