Maaz
Maaz

Reputation: 4303

qsort in C with structures, some problems

void sortSchedule (struct event schedule[], int n)
{
    qsort(schedule, n, sizeof(struct event), compare());
}

int compare(const void * a, const void * b)
{
    const struct event *evA = a;
    const struct event *evB = b;

    int startA = evA.start.hour*60 + evA.start.minute;
    int startB = evB.start.hour*60 + evB.start.minute;

    return ( startA - startB );
}

My Structure

struct tod {
  int hour, minute;
};


struct event {
  struct tod start, end;
};

Just using compare instead of compare(), the compiler seems to treat it as a variable instead.

Secondly, I'm wondering if my compare function is correct? Since i'm getting some errors from the compiler, more specifically the following

Error: request for member 'start' in something not a structure or union

^ that error occurs for this line int startA = evA.start.hour*60 + evA.start.minute;

So I assume it thinks that evA is not a structure even though I explicitly declared it as such. This might be because I haven't properly declared it, any help would be appreciated :)

Upvotes: 0

Views: 66

Answers (2)

pjhades
pjhades

Reputation: 2038

You should use -> to reference the structure member if you're doing this with pointers:

int startA = evA->start.hour*60 + evA->start.minute;
int startB = evB->start.hour*60 + evB->start.minute;

And your call to qsort should be:

qsort(schedule, n, sizeof(struct event), compare);

since the fourth argument is a pointer to a function.

Upvotes: 1

fpw
fpw

Reputation: 799

Since evA and evB are pointers, you have to use evA->member instead of evA.member.

Upvotes: 2

Related Questions