0

I tried to sort a struct with qsort(), by using pointers to the struct objects. But when I try to run the program I get an access violation error thrown. I'm lost.

This is my array:

 struct studenten_typ sfeld[] = {
    { 123456, 1273.17, { "Erna", "Schlaukopf" } },
    { 213456, 1273.17, { "Erna", "Meier" } },
    { 423456, 1373.67, { "Emil", "Meier" } },
    { 473456, 1193.17, { "Anton", "Mueller" } },
    { 503456, 1473.17, { "Anna", "Mueller" } },
    { 523456, 1063.17, { "Max", "Muster" } },
    { 573456,  945.17, { "Eva", "Muster" } },
    { 723456, 1123.17, { "Xaver", "Kurz" } },
    { 953456, 1273.17, { "Erna", "Schlaukopf" } },
    { 773456, 1243.17, { "Karl", "Kurz" } }
};

This is my qsort function in main (here is where I get the error)

qsort(&sfeld[0], sfeld_n, sizeof(sfeld), stud_matrnr_aufst_vgl_fkt_ptr);

And here is my comparing function

int stud_matrnr_aufst_vgl_fkt_ptr(const void*v1_ptr, const void*v2_ptr)
{
    struct studenten_typ* p1 = (void*)v1_ptr;
    struct studenten_typ* p2 = (void*)v2_ptr;
    // .... ???
    if (p1->matrikel_nr > p2->matrikel_nr)
        return 1;
    if (p1->matrikel_nr < p2->matrikel_nr)
        return -1;
    if (p1->matrikel_nr == p2->matrikel_nr)
        return 0;
}

And my struct is this:

struct studenten_typ {
    /** Matrikelnummer als eindeutiges Kriterium */
   int matrikel_nr;
    /** Monatsgehalt der DH-Studenten*/
    double gehalt;
    /** Name. */
    struct namens_typ name;
}
KazikM
  • 1,257
  • 5
  • 21
  • 29
Tsipi
  • 9
  • 1
  • 2
    Have you tried running your code line by line in a debugger while monitoring the values of all variables, in order to determine at which point your program stops behaving as intended? If you did not try this, then you probably want to read this: [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/12149471) You may also want to read this: [How to debug small programs?](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Andreas Wenzel Dec 05 '20 at 21:08
  • 1
    The `qsort` size parameter is the size of each element not the size of the entire array. So `sizeof(sfeld)` should be `sizeof(sfeld[0])`. – kaylum Dec 05 '20 at 21:11

1 Answers1

3

The qsort size parameter is the size of each element not the size of the entire array. From the man page:

The qsort() function sorts an array with nmemb elements of size size.

So sizeof(sfeld) should be sizeof(sfeld[0]).

kaylum
  • 13,833
  • 2
  • 22
  • 31