Skip to main content
2 of 5
edited tags
200_success
  • 145.7k
  • 22
  • 191
  • 481

Compress a function

So I have this function:

int sort(book *data, int books, char mode, char sortBy) { int i, j; book aux; aux.cat = malloc(sizeof *(aux.cat)); if(sortBy == 'n') { for(i = 0; i < books; i++) { for(j = i; j < books; j++) { if(mode == 'a') { if(strcmp((data + i)->fname, (data + j)->fname) > 0) { aux = *(data + i); *(data + i) = *(data + j); *(data + j) = aux; } } else { if(strcmp((data + i)->fname, (data + j)->fname) < 0) { aux = *(data + i); *(data + i) = *(data + j); *(data + j) = aux; } } } } } else { for(i = 0; i < books; i++) { for(j = i; j < books; j++) { if(mode == 'a') { if(strcmp((data + i)->categ, "Fictiune") == 0) { if(((data + i)->cat)->price > ((data + j)->cat)->price) { aux = *(data + i); *(data + i) = *(data + j); *(data + j) = aux; } } } else { if(strcmp((data + i)->categ, "Fictiune") == 0) { if(((data + i)->cat)->price < ((data + j)->cat)->price) { aux = *(data + i); *(data + i) = *(data + j); *(data + j) = aux; } } } } } } free(aux.cat); return 0; } 

I need to sort the *data array in two modes: ascending, and descending, and by two criterias: name, and price.

The question is: is there a way to write another more compact function that will do the same thing?

And, what do you think about line 5 (aux.cat = malloc(sizeof *(aux.cat));)? It's a right way to initialize *cat pointer?

This are the structures:

typedef struct { int price, edition; char favCharacter[SMAX]; } category; typedef struct { char title[SMAX], fname[SMAX], lname[SMAX], categ[SMAX]; category *cat; } book; 
mariusmmg2
  • 271
  • 3
  • 7