First, I defined a dynamic array with 2 columns and 10 row. The integer number
is set to 10 here just for example.
int** array;
int number = 10;
array = malloc(number * sizeof(int*));
for (i = 0; i < number; i++)
array[i] = malloc(2 * sizeof(int));
Then I try to use qsort()
on it.
qsort( array, number, sizeof array[0], compare );
This is my compare function. It sorts by the integer values in the first column, then sorts by the second column while preserving the order in the first column. E.g. "0 2, 1 7, 0 1" will become "0 1, 0 2, 1 7".
int compare ( const void *pa, const void *pb ) {
int (*a)[1] = pa;
int (*b)[1] = pb;
if ( (a[0][0] < b[0][0]) || (a[0][0] == b[0][0])&&(a[1][0] < b[1][0]) ) return -1;
if ( (a[0][0] > b[0][0]) || (a[0][0] == b[0][0])&&(a[1][0] > b[1][0]) ) return +1;
return 0;
}
Question
This worked with a static array. I know it doesn't work now because I have a dynamic array, which is an array of pointers.
How can I adapt this code to work with the dynamically created multi-dimensional array?