Home > Net >  sorting an array of strings with qsort function
sorting an array of strings with qsort function

Time:03-07

I'm sorting an array of strings by using the qsort function.

char treeName[100][31];

By trial and error, I figured out that it should be done like this:

qsort(&treeName[0], count, sizeof(*treeName), Comparar_nome);

However, I am not entirely sure why sizeof(*treeName). Shouldn't it be sizeof(char) * 31, or something like that?

CodePudding user response:

   qsort(&treeName[0], count, sizeof(*treeName),Comparar_nome);

Can be broken down as follows:

    qsort

The function call.

    &treeName[0]

Address of the start of the array. Can be simplified to treeName.

    count

The number of entries in treeName actually used.

    sizeof(*treeName)

The size of an array element. I would have written this is sizeof(treename[0]) but there's no difference. sizeof(char)*31 really should have worked. Are you sure you didn't have something else broken when you tried it? We were unable to find a real compiler for which this would not work. sizeof(*treename) is better anyway for readability and should that 31 ever change.

    Comparar_nome

Address of the function that compares tree nodes. You wrote it correctly; &Comparar_nome is archaic style.

CodePudding user response:

If treeName is indeed defined as char treeName[100][31]; in the scope of the function calling qsort, your code is correct:

qsort(&treeName[0], count, sizeof(*treeName), Comparar_nome);

You could write this equivalently:

qsort(treeName, count, sizeof treeName[0], Comparar_nome);

Note however that Comparar_nome must have the correct prototype:

int Comparar_nome(const void *a, const void *b);

A simple implementation being:

#include <stdio.h>

int Comparar_nome(const void *a, const void *b) {
    return strcmp(a, b);
}

Passing strcmp instead of Comparar_nome would be a type mismatch invoking undefined behavior that would go unnoticed in many architectures but is nevertheless incorrect.

  • Related