I wrote the following code for counting the frequency of names and then printing out the names in lexicographic order with their frequencies.The input here is supposed to be n number of names.So for sorting i wrote qsort function but i guess there is some error in it which i am not able to find bcoz using using other sorting method besides qsort works fine for this code.Please suggest what is the error as i have tried but found no help.below is the code snippet
#include <cstdlib>
#include<stdio.h>
#include<string.h>
struct stu
{
char name[100];
int no;
};
int cmpfunc(const void* p,const void *q){
struct stu *a = *((struct stu**)p);
struct stu *b = *((struct stu**)q);
int str=strcmp(a->name,b->name);
if(str>0) return 1;
if(str<0) return -1;
else return 0;
}
int main(int argc, char** argv) {
int n,k=0;
scanf("%d",&n);
struct stu* data[1000];
for(int i=0 ; i<n ; i++)
{
char nam[100];
scanf("%s",nam);
if(i==0)
{
struct stu* temp=(struct stu*)(malloc(sizeof(struct stu)));
strcpy(temp->name,nam);
temp->no=1;
data[k++]=temp;
}
else
{
int j;
for(j=0 ; j<k ; j++)
{
if(strcmp(data[j]->name,nam)==0)
{
data[j]->no++;
break;
}
}
if(j==k)
{
struct stu* temp=(struct stu*)(malloc(sizeof(struct stu)));
strcpy(temp->name,nam);
temp->no=1;
data[k++]=temp;
}
}
}
qsort(data, k, sizeof(struct stu*),cmpfunc);
for(int i=0 ; i<k ; i++)
{
printf("%s %d\n",data[i]->name,data[i]->no);
}
return 0;
}
if i give input as
5
abcd
abcd
fgh
fgr
fgh
the output is run failed