Below is a sample program that shows 1) how to call the qsort
function for each dynamically allocated sub-array, and 2) how to write a comparison function to sort.
#include <stdio.h> #include <stdlib.h> #include <time.h> int cmp( const void *a, const void *b ) { int left = *( const int * )a; int right = *( const int * )b; return ( right < left ) - ( left < right ); } int main( void ) { const int N = 10; int **a = malloc( N * sizeof( int * ) ); srand( ( unsigned int )time( NULL ) ); for ( int i = 0; i < N; i++ ) { a[i] = malloc( ( i + 2 ) * sizeof( int ) ); a[i][0] = i + 1; for ( int j = 0; j < a[i][0]; j++ ) a[i][j+1] = rand() % ( N * N ); } for ( int i = 0; i < N; i++ ) { for ( int j = 0; j < a[i][0]; j++ ) printf( "%d ", a[i][j +1] ); putchar( '\n' ); } putchar( '\n' ); for ( int i = 0; i < N; i++ ) { qsort( a[i] + 1, a[i][0], sizeof( int ), cmp ); } for ( int i = 0; i < N; i++ ) { for ( int j = 0; j < a[i][0]; j++ ) printf( "%d ", a[i][j+1] ); putchar( '\n' ); } for ( int i = 0; i < N; i++ ) free( a[i] ); free( a ); return 0; }
The output of the program to the console, for example, may look like this:
47 48 42 34 10 24 28 89 72 97 12 71 81 60 2 8 87 48 13 27 74 58 19 44 54 24 55 86 25 72 71 72 21 65 59 83 90 87 24 62 85 36 33 18 96 87 26 84 88 92 63 62 50 82 7 47 42 48 10 24 34 28 72 89 97 2 12 60 71 81 8 13 27 48 74 87 19 24 44 54 55 58 86 21 25 59 65 71 72 72 83 18 24 33 36 62 85 87 90 96 7 26 50 62 63 82 84 87 88 92
&array[i][1]
. - Harryarray[i][1]
. - Harry