andybelous andybelous - 2 months ago 13
C Question

Cant sort array of struct

I have an array of struct,that I read from the text file.I wrote a sort function,that has to sort this array by the name field in alphabet order(A-Z),but it doesnt work,i dont know what to do,plz,can you tell me my mistake(code compiles,but it doesnt sort anything).

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int my_compare(const void*,const void*);
typedef struct {
char name[100];
char surname[100];
char sname[100];
char posada[100];
char buff[100];
int staz;
char buff2[100];
int oklad;
} test;
;
int main()
{
test mass[7];
/* struct test{
char name[100];
char surname[100];
char sname[100];
char posada[100];
char buff[100];
int staz;
char buff2[100];
int oklad;
}mass[8]
;
*/
FILE *fo;
if((fo=fopen("C:\\Users\\andyb\\Desktop\\test2.txt","r"))==NULL)
printf("error");
for(int i=0;i<7;i++)
{
fgets(mass[i].name,50,fo);
fgets(mass[i].surname,50,fo);
fgets(mass[i].sname,50,fo);
fgets(mass[i].posada,50,fo);
fgets(mass[i].buff,50,fo);
mass[i].staz=atoi(mass[i].buff);
fgets(mass[i].buff2,50,fo);
mass[i].oklad=atoi(mass[i].buff2);
}
fclose(fo);
for(int i=0;i<7;i++)
{
printf("%s%s%s%s%d\n%d\n",mass[i].name,mass[i].surname,mass[i].sname,mass[i].posada,mass[i].staz,mass[i].oklad);
}
qsort( mass, sizeof(mass)/sizeof(mass[0]), sizeof(mass[0]), my_compare );
for(int i=0;i<7;i++)
{
printf("%s%s%s%s%d\n%d\n",mass[i].name,mass[i].surname,mass[i].sname,mass[i].posada,mass[i].staz,mass[i].oklad);
}


return 0;
}

int my_compare(const void *a,const void *b)
{
const test *pa = (const test *)a;
const test *pb = (const test *)b;

return strcmp( pa->name, pb->name );
}

Answer

Your for loops look incorrect:

Instead of this:

for(int i=1;i<8;i++)

You should be saying this:

for(int i=0;i<8;i++)

Otherwise, mass[0] is going to contain garbage data and all sorts of undefined behavior will occur when you try to sort against it.