-1

Suppose I have a struct Sentence and a struct Text. How do I implement qsort on capital_letters_quant? How can you write out the same compare function?

struct Sentence {
    wchar_t* sentence_text;
    size_t sentence_size;   
    bool is_sentence_anagram;
    int64_t capital_letters_quant;
};

struct Text {
    struct Sentence* full_text;
    size_t full_text_size;
};

So, I tried to change the arguments of the compare function to struct Sentence *, but the compiler gave warnings or errors, I would not want to receive them, to be honest...

This is my atmpt to do it

int second_compare(const void* first_current_sentence, const void* second_current_sentence) {
    return ((struct Sentence*)second_current_sentence -> capital_letters_quant) - ((struct Sentence*)first_current_sentence -> capital_letters_quant);
}

But gcc send me this

error: conflicting types for 'second_compare'; have 'int(const void *, const void *)'

note: previous declaration of 'second_compare' with type 'int(struct Sentence *, struct Sentence *)'

warning: dereferencing 'void *' pointer

error: request for member 'capital_letters_quant' in something not a structure or union

error: request for member 'capital_letters_quant' in something not a structure or union

1 Answers1

0
  • First, you should change your declaration of second_compare to int second_compare (const void *, const void *); because the types of arguments in declaration and in definition must be the same.
  • Second, the -> operator has greater priority relatively to cast operator (struct Sentence *), which means that compiler first tries to access field capital_letters_quant in the structure pointed to by the void pointer, thus it tries to dereference it. To fix this, you should first cast, then dereference: ... ((struct Sentence *) data) -> field ....
  • Third, your function takes two pointers, referencing constant values (as far as you marked them with const). But in the body of function you cast these values to non-constant values of type (struct Sentence *), whilst you should cast to constant values of type (const struct Sentence *).
Sasha Shibaev
  • 11
  • 2
  • 2