Domanda

I'm a beginner when it comes to pointers and recently for an assignment I was asked to write a function that would take in beginning and end pointers to an array and then sort them with qsort. Here is what I have:

int isort(int* begin, int* end)
{
    int length = 0;

    while((begin != end)){
            begin++;
            length++;
    }

   size_t array_len = length;
     qsort((void *)begin, array_len, sizeof(int), int_cmp);

    return length;
}

So my idea was to have the while loop get the length of the array (which works), but I'm struggling on the actual qsort part as to what to put in the for the first parameter (I think my problem is there). For errors I get a bunch of memory map and backtrace stuff.

Thanks for any help.

È stato utile?

Soluzione

You modify begin in your loop, so you lost that pointer and you end up calling qsort with the wrong pointer. How about something saner like this:

int isort(int * const begin, int * const end)
{
    qsort(begin, end - begin, sizeof(int), int_cmp);
    return end - begin;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top