Programming Problems Using Structure 279
// get add r esses of the array elements117
const Person * * pp1 = ( const Person * *) p1 ;118
const Person * * pp2 = ( const Person * *) p2 ;119
// get the elem e nts120
const Person const * pv1 = * pp1 ;121
const Person const * pv2 = * pp2 ;122
// compare the attribu tes123
return strcmp (( pv1 -> name ) , ( pv2 -> name )) ;124
}125
void Pers on_so rtByN a me ( Pe rsonDa tabase * perdb )126
{127
qsort ( perdb -> person , perdb -> number ,128
s i z e o f ( Person *) , comp a rebyNa me ) ;129
}130
s t a t i c i n t com p arebyAg e ( const void * p1 ,131
const void * p2)132
{133
const Person * * pp1 = ( const Person * *) p1 ;134
const Person * * pp2 = ( const Person * *) p2 ;135
const Person * pv1 = * pp1 ;136
const Person * pv2 = * pp2 ;137
return (( pv1 -> age ) - ( pv2 -> age )) ;138
}139
void Pers on_sor tByAg e ( Pers onData base * perdb )140
{141
qsort ( perdb -> person , perdb -> number ,142
s i z e o f ( Person *) , compa rebyAge ) ;143
}144
void Pers o n_des truct ( Pers onData b ase * perdb )145
{146
int ind ;147
for ( ind = 0; ind < perdb -> number ; ind ++)148
{149
free ( perdb -> person [ ind ] -> name );150
free ( perdb -> person [ ind ]);151
}152
free ( perdb -> person );153
free ( perdb ) ;154
}155
This is the main function:
// main . c1
#in clude < stdio .h >2
#in clude < stdlib .h >3
#in clude < string .h >4
#in clude " person .h "5
int main ( i n t argc , char * argv [])6
{7
// argv [1]: name of input file8
// argv [2]: name of output file ( sort by name )9
// argv [3]: name of output file ( sort by age )10