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,
Not terribly efficient, but your structs are small, so its only a bit more expensive than swapping pointers.
John has already answered your question, but to sort your
struct
s, you can use the standard libraryqsort()
function:The output of the program is:
The advantage is that
qsort()
is standard, and you can use it to sort anything.You could just let someone else think about this, i.e. use
qsort()
: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 usesmemcpy()
), but it's way easier to write and much easier to maintain.