I'm attempting to sort an array of structs in a struct based on an int value. I've successfully sorted an array of structs but I'm guessing I'm passing a wrong value somewhere for the nested structs.
I just need the structs in the array sorted the value of a.
The structs are set up as:
struct s2{
int a;
int b;
};
struct s1{
int c;
struct s2 arr[10];
}
I have a compare function:
int comp(const void *a, const void *b){
struct s1 *q1 = (struct s1 *)a;
struct s1 *q2 = (struct s1 *)b;
return(q1->arr->a - q2->arr->a);
}
And I call qsort:
struct s1 myStruct;
size_t theLen = sizeof(myStruct.arr) / sizeof(struct s2);
qsort(myStruct.arr, 10, theLen, comp);
For the input:
10, 5, 7, 20, 17, 9, 3, 11, 15, 1
I get output:
2147451181, 589824, 327680, 65536, 131072, 4, 5, 11, 15, 8
I'm guessing it may be something to do with how I declare the length?
Thanks!
The file line is:
10 5 7 20 17 9 3 11 15 1
myStruct.arr[i].a is filled from file input using fgets and sscanf:
fgets(t, sizeof(t), fp);
sscanf(t, "%d,...,%d", &myStruct.arr[0].a,...,&myStruct.arr[9].a);
myStruct.arr[i].b is filled with a for loop:
for(int i = 0; i < 10; i++){
myStruct.arr[i].b = i+1;
}