Hi,

I am trying to q-sort an 2D array containing 2 columns of floats. The array must be sorted on the basis of any one of the columns.

This is the code that I wrote..

As I understand it, every element in array[], is a pointer to a pointer to a float.. (float**).Code:int compare( const void* a, const void* b) { float** p1 = (float**) a; float** p2 = (float**) b; if( p1[1] > p2[1]) { return -1; } else if (p1[1] < p2[1]) { return 1; } else { return 0; } } int main() { float **array; int i; array = (float**)malloc(10*sizeof(float*)); for(i=0; i<10; i++) { array[i] = (float*)malloc(2*sizeof(float)); } for(i=0; i<10; i++) { array[i][0] = i; array[i][1] = 2*i; } for( i=0; i<10; i++) { printf("%f\t%f\n",array[i][0],array[i][1]); } printf("\n\n"); qsort(array, 10, sizeof(float**),compare); for( i=0; i<10; i++) { printf("%f\t%f\n",array[i][0],array[i][1]); } return 0; }

So I m passing this float** to the compare function and inside the function I am asking it to look at the second element in the row pointed to by this float ** and return 1, -1 or 0.

But the output from this code is in random order and is not sorted at all. However if I run it with

i.e. if I ask it to sort by the 1st element of each row instead of the second, the output is properly sorted.Code:if( p1[1] > p2[1]) { return -1; } else if (p1[1] < p2[1]) { return 1; } else { return 0; }

I think the place I m going wrong is probably in the type casting inside the compare function. But I m not able to get it. Can anyone tell me what I am doing wrong..

thanks,

Avinash