I can not understand why qsort does not work for strings of a dynamic two-dimensional array:

#include <QCoreApplication> #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include<malloc.h> #include<stdlib.h> int cmp(const void *a, const void *b) { return *(int*)a - *(int*)b; } int** array_sort(int** array,int width) { for(int i=0;i<width;i++) { qsort(array[i],array[i][0],sizeof(int),cmp); } } 

The first element of each line of the array stores the number of elements in this line, so I need to sort, starting with array [i] [1].

  • one
    And which array and how you transfer is one time, and the second is the width, which is actually a width :), i.e. according to the logic, the number of columns (does not apply to the correctness of the code). Well, the first then it is necessary to transfer argument &array[i][1] . - Harry
  • @Harry thanks & array [i] [1] worked, did not think of the link to transmit - makc2099
  • one
    This is not a link, but the address of array[i][1] . - Harry

1 answer 1

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