Domanda

I have a structure that I need to sort in ascending order:

typedef struct CallLogSearchDataStruct
{
    char * date;
    char * time;
    char * bParty;
    char * aParty;
    float duration;
    char * cleardownCause;
    struct CallLogSearchOutboundStruct * outboundLegs;
    int maxDataCol;
} callLogSearchDataStruct;

I need to sort the structure based on the date and time in ascending order. The date and time is in the following format

Date: 16/05/2011 Time: 01:20:03

I need to sort the above two fields in ascending order, and I've been looking at qsort but I can't figure out a way of being able to do it. I am calling the function in the following way.

qsort(callLogSearchData, dataRow, sizeof(callLogSearchDataStruct), sortCompare);

And my function is as follows

int sortCompare(const void * a, const void * b)
{
    const callLogSearchDataStruct *u1 = a;
    const callLogSearchDataStruct *u2 = b;

    if (u1->date < u2->date)
    {
        return -1;
    }
    else if (u1->date > u2->date)
    {
        return 1;
    }
    else
    {
        return 0;
    }

}

When I do the above code, it doesn't seem to sort it and instead screws up the layout of the structure, i.e. when I export the contents of the structure to a file, everything comes out in the wrong column order, whereas it is fine, except for being in the wrong sort order if the compare is not done.

È stato utile?

Soluzione

You are comparing pointers, which is certainly not what you are looking for. Here's one approach to compare the structs:

  • Parse the strings and extract individual components like year, month day etc
  • Fill a struct tm with required details and call mktime on it
  • At this point you've got 2 time_t values which you can compare using difftime

This sounds like a lot of work, and it is! If you're willing to go a little non-portable you can try the wonderful strptime which converts strings to struct tms.

Altri suggerimenti

It seems you are comparing character pointers and based on that you are making decisions.But you have to compare Date and Time values for sorting. As they both are strings,you should parse strings,get year,months,date,hours,sec in different variables. Now you can use

mktime()

it will return you it in time_t format.Now you can easily compare them and sort accordingly.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top