0

I need to write a comparison function for qsort for structs with pointer members. Let's say I have

struct foo2_struct
{
    int a;
}

struct foo1_struct
{
    int a;
    struct foo2_struct *b;
}

Here's what I have:

int cmp_foo1(const void *a, const void *b)
{
    struct foo1_struct foo1a = *((struct foo1_struct) a);
    struct foo1_struct foo1b = *((struct foo1_struct) b);
    int cmp = foo1a.a - foo1b.a;
    if (cmp == 0)
    {
        if (foo1a.b == foo1b.b)
            return 0;
        //how to continue???
    }
    return cmp;
}

Note that foo2_struct member b is not unique, as in, two different variables of this type can have the same value of b.

Dunno
  • 3,632
  • 3
  • 28
  • 43
  • If you want to compare `int a` members of the `foo2_struct`s they point to (rather than the values of the pointers themselves, I think you just return `a.b->a - b.b->a` when `cmp` is zero. – TripeHound Jun 17 '15 at 13:25
  • you are copying the struct. i bet that's not necessary. change it to pointer operation should be better. – Jason Hu Jun 17 '15 at 13:29
  • When you say _how to continue???_ You may decide what is the most relevant for sorting 'a' or 'b' value! Please think of the order you want and give us an example. – prodev_paris Jun 17 '15 at 13:29
  • @prodev_paris I think I've run into the xy problem. The next thing I need to do is delete duplicates, that's why I'm so concerned about the cases in which this function might return 0 – Dunno Jun 17 '15 at 13:34
  • @Dunno if your concern is more like comparing equality of struct please see :http://stackoverflow.com/a/141724/4716013 But in fact it said that you have to code it yourself ;) – prodev_paris Jun 17 '15 at 13:39

1 Answers1

1

Simply replace

int cmp = a.a - b.a;
[...]
if (a.b == b.b)

by

int cmp = foo1a.a - foo1b.a;
[...]
if (foo1a.b == foo1b.b)

Since you must use the structure not void pointers...

EDIT

In addition you may compare the value inside the struct not the pointer to the struct (but I do not know your goal anyway...) So replace

if (foo1a.b == foo1b.b)

by

if (foo1a.b->a == foo1b.b->a)

Note: I let you handle the NULL scenario :)

prodev_paris
  • 495
  • 1
  • 4
  • 17