1

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?

2
  • 2
    Did you try using sizeof(char) * 31? It should work as well as either sizeof(*treeName) or sizeof(treeName[0]) (or slightly less plausible constructs, such as sizeof(char[31])). All of these evaluate to the same number — 31. Commented Mar 6, 2022 at 5:43
  • Post Comparar_nome(). Commented Mar 6, 2022 at 6:59

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1
   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.

1 Comment

Comments are not for extended discussion; this conversation has been moved to chat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.