Question

I've implemented this struct in C:

typedef struct student_type_ {                  
    int number;                              
    char name[20];                       
    char lastname[20];                       
    struct student_type_ *next_student;        
} student_type;

and now I want to sort a list of this structs by name and last name. Therefore I want to create 2 functions "compare" with different parameters: one function gets 2 pointers to 2 names and the other to 2 last names.

Something like this:

int compare ((*student_type)->name a, (*student_type)->name b){
    return strcmp(*a, *b);
}

int compare ((*student_type)->lastname a, (*student_type)->lastname b){
    return strcmp(*a, *b);
}

this code is not correct. Can you help me to identify and solve the problem?

Thank you!

Was it helpful?

Solution 3

To define two functions with the same name in C constitutes a sin. In your case, what you really want is probably one of two things. Either define two functions:

  • compare_by_first_name
  • compare_by_last_name

with the obvious functionality, or, alternatively, one function: compare(char * name1, char * name2) which is then called as such:

compare (student1->name, student2->name);
compare (student1->lastname, student2->lastname);

OTHER TIPS

You could try

int compare_by_name(student_type * a, student_type * b){
    return strcmp(a->name, b->name);
}

int compare_by_lastname(student_type * a, student_type * b){
    return strcmp(a->lastname, b->lastname);
}

if you want to use it in conjunction with bsort(), you might need to use void * instead for the parameters.

The problem is that student_type->lastname is not a type, neither is student_type->name. Try char*

When you fix that you will run into the problem that in C a function with the same parameter cannot have two names (C doesn't support overloading) so you will have to write two compares, one that implements the rules to compare names and another on to implement the comparison of last names (if for whatever reason the rules are different).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top