Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping elements in an array of structs

Tags:

c

pointers

struct

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?

like image 493
Pieter Avatar asked May 25 '26 11:05

Pieter


2 Answers

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.

like image 200
John Knoeller Avatar answered May 28 '26 02:05

John Knoeller


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.

like image 25
unwind Avatar answered May 28 '26 01:05

unwind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!