Сортировка qsort для структуры - C (СИ)
Формулировка задачи:
Здравствуйте. Очень надеюсь на вашу помощь. Пытаюсь оседлать функцию qsort() на C. Есть определённые проблемы. Программа выводит не правильно отсортированный массив строк или чисел (есть и то, и другое в структуре) и тут же вылетает. Компилятор: MS VS 2012 EE. Посмотрите код. Я знаком с этим языком только 6 недель, в ВУЗе не на шутку торопят процесс, так что осознать всё нормально не успеваю.
Задача изначально такая: Написать программу, в которой есть структура, содержащая и сортирующая элементы: название книги, автор (имя и фамилия), стоимость.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#define un 250
struct books {char title[un]; char authorFirst[un]; char authorLast[un]; int value[un]; char booksis[un]; };
int QUICKsort_FL(const void *sortI, const void *sortJ) //реализация функции qsort
{//return *(int*)sortI-*(int*)sortJ;
const struct books *sortI1=(const struct books*) sortI;
const struct books *sortJ2=(const struct books*) sortJ;
int t;
t=strcmp(sortI1->authorLast, sortJ2->authorLast); //сравнили фамилии
if (t!=0) {return t;} else {return strcmp(sortI1->authorFirst, sortJ2->authorFirst);} //сравнили имена, когда фамилии совпадают
}
int QUICKsort_VALUE(const void *sortI, const void *sortJ) //реализация функции qsort (возрастание), для убывания поменять return на противоположные
{//return *(int*)sortI-*(int*)sortJ;
const struct books *sortI1=(const struct books*) sortI;
const struct books *sortJ2=(const struct books*) sortJ;
if (sortI1<sortJ2) {return -1;} else if (sortI1==sortJ2){return 0;} else {return 1;}
}
int QUICKsort_TITLE(const void *sortI, const void *sortJ) //реализация функции qsort
{//return *(int*)sortI-*(int*)sortJ;
const struct books *sortI1=(const struct books*) sortI;
const struct books *sortJ2=(const struct books*) sortJ;
int t;
t=strcmp(sortI1->authorLast, sortJ2->authorLast);
if (t!=0) {return t;} else {return strcmp(sortI1->authorFirst, sortJ2->authorFirst);}
}
int variants(void)
{int b=0;
printf("Chto vi hotite dalee? Enter number: ");
printf("\n1-Posmotret' spisok zakazannih knig v poradke sakazivanija\n");
/* printf("2-Otsortirovat' po ubivaniyu ceni\n");*/
printf("2-Otsortirovat' po vozrastaniju ceni\n");
printf("3-Otsortirovat' po avtoru a-ja \n");
/*printf("5-Otsortirovat' po avtoru ja-a \n");*/
printf("4-Otsortirovat' po nazvaniyu a-ja \n");
/*printf("7-Otsortirovat' po nazvaniyu ja-a \n");*/
printf("5-Udalit' element \n");
printf("6-Dobavit' element \n");
scanf_s("%d", &b);
return 0;
}
int main (void)
{struct books booksA[un];
//struct people peopleA[un];
int i,j,a,b,c,sortI, sortJ,*help;
char *helpchar1;
char *helpchar2;
char *helpchar3;
char *helpchar4;
c=0;
printf("Chtoby prervat' vvod i pereyti k novomy shagu nagmite ENTER posle soobjeniya o vvode novoy knigi\n");
printf("Vvedite nazvanie knigi (<%d) # %d\n", un, c) ;
while ((c<un)&&(gets_s(booksA[noparse][c][/noparse].title)!=NULL)&&(booksA[noparse][c][/noparse].title[0]!='\0')) //условия произведения ввода: заполненность структуры, наличие вводимых данных.
{printf("Vvedite First name avtora knigi #%d\n",c);
gets_s(booksA[noparse][c][/noparse].authorFirst);
printf("Vvedite Last name avtora knigi #%d\n",c);
gets_s(booksA[noparse][c][/noparse].authorLast);
printf("Vvedite cenu knigi(celoe) #%d\n",c);
scanf_s("%f", &booksA[noparse][c][/noparse].value);
c++;
while (getchar()!='\n') {continue;} //продолжаем ввод пока не нажат Enter
if (c<un) {printf("\nVvodite nazvanie sledujushey knigi # %d\n", c);}
}
// b=getch();
variants();
if ((c!=0)&&(b=1))
{printf("Spisok zakazannih knig: \n");
for (i=0; i<c; i++)
{printf("%s by %s %s: (rub) %d\n", booksA[i].title, booksA[i].authorFirst, booksA[i].authorLast, booksA[i].value);}
}
else
{printf("Ne vibraly? Its bad!\n"); return 0;}
if ((c!=0)&&(b=2))
{qsort(booksA, un, sizeof(struct books), QUICKsort_VALUE); //по возрастанию цены
for (i=0; i<c; i++) {printf("%s", booksA[i]);};
}
if ((c!=0)&&(b=3))
{qsort(booksA, un, sizeof(struct books), QUICKsort_FL); //по автору а-я
for (i=0; i<c; i++) {printf("%s", booksA[i]);};
}
if ((c!=0)&&(b=4))
{qsort(booksA, un, sizeof(struct books), QUICKsort_TITLE); //по названию а-я
for (i=0; i<c; i++) {printf("%s", booksA[i]);};
}
system("pause");
return 0;
}Решение задачи: «Сортировка qsort для структуры»
textual
Листинг программы
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#define un 250
struct books {char title[un]; char authorFirst[un]; char authorLast[un]; int value; char booksis[un]; };
int QUICKsort_FL(const void *sortI, const void *sortJ) //реализация функции qsort
{
const struct books *sortI1=(const struct books*) sortI;
const struct books *sortJ2=(const struct books*) sortJ;
int t;
t=strcmp(sortI1->authorLast, sortJ2->authorLast); //сравнили фамилии
if (t!=0) {return t;} else {return strcmp(sortI1->authorFirst, sortJ2->authorFirst);} //сравнили имена, когда фамилии совпадают
}
int QUICKsort_VALUE(const void *sortI, const void *sortJ) //реализация функции qsort (возрастание), для убывания поменять return на противоположные
{
int sortI1=(const struct books *)sortI->value;
int sortJ2=(const struct books *)sortJ->value;
if (sortI1<sortJ2) {return -1;} else if (sortI1==sortJ2){return 0;} else {return 1;} //тоже самое, что return sortI1 - sortJ2;
}
int QUICKsort_TITLE(const void *sortI, const void *sortJ) //реализация функции qsort
{
const struct books *sortI1=(const struct books*) sortI;
const struct books *sortJ2=(const struct books*) sortJ;
int t;
t=strcmp(sortI1->title, sortJ2->title);
if (t!=0) {return t;}
}
int main (void)
{struct books booksA[un];
int i,j,a,b,c,sortI, sortJ,*help;
c=0;
if (b==2)
{qsort(booksA, un, sizeof(struct books), QUICKsort_VALUE); //по возрастанию цены
for (i=0; i<c; i++) {printf("%s by %s %s: (rub) %d\n", booksA[i].title, booksA[i].authorFirst, booksA[i].authorLast, booksA[i].value);} ;
}
else if ((c=0)||((b>6)&&(b<1))) {printf("Ne vibraly? Its bad!\n"); return 0;}
if (b==3)
{qsort(booksA, un, sizeof(struct books), QUICKsort_FL); //по автору а-я
for (i=0; i<c; i++) {printf("%s by %s %s: (rub) %d\n", booksA[i].title, booksA[i].authorFirst, booksA[i].authorLast, booksA[i].value);};
}
else if ((c=0)||((b>6)&&(b<1))) {printf("Ne vibraly? Its bad!\n"); return 0;}
if (b==4)
{qsort(booksA, un, sizeof(struct books), QUICKsort_TITLE); //по названию а-я
for (i=0; i<c; i++) {printf("%s by %s %s: (rub) %d\n", booksA[i].title, booksA[i].authorFirst, booksA[i].authorLast, booksA[i].value);};
}
else if ((c=0)||((b>6)&&(b<1))) {printf("Ne vibraly? Its bad!\n"); return 0;}