構造体の配列をint値に基づいてソートしようとしています。私は正常に構造体の配列をソートしましたが、私は入れ子構造体のどこかで間違った値を渡していると思います。qsort構造体の配列の配列
私は配列の構造体にaの値をソートするだけでいいです。
構造体は以下のように設定されています
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);
}
そして、私はqsortを呼び出す:私は比較する機能を持っている
struct s2{
int a;
int b;
};
struct s1{
int c;
struct s2 arr[10];
}
入力の場合
struct s1 myStruct;
size_t theLen = sizeof(myStruct.arr)/sizeof(struct s2);
qsort(myStruct.arr, 10, theLen, comp);
:
を10, 5, 7, 20, 17, 9, 3, 11, 15, 1
私は出力を得る:
2147451181, 589824, 327680, 65536, 131072, 4, 5, 11, 15, 8
は、私は私が長さを宣言する方法とは何かかもしれ推測していますか?
ありがとうございます!
ファイルの行は、次のとおり
10 5 7 20 17 9 3 11 15 1
myStruct.arr [I] .Aは関数fgetsとsscanf関数を使用して、ファイル入力から充填される。
fgets(t, sizeof(t), fp);
sscanf(t, "%d,...,%d", &myStruct.arr[0].a,...,&myStruct.arr[9].a);
myStruct.arr [i]は.Bでありますforループでいっぱい:
for(int i = 0; i < 10; i++){
myStruct.arr[i].b = i+1;
}
私は、OPのキャストが間違っていると付け加えます(そして、無効な 'void const *'は自動昇格です)。なぜならそれはconstの修飾子を破棄しているからです: 'struct s2 const * q1 = a; struct s1 const * q2 = b; ' – Stargateur
@Stargateurありがとう、私はメモを追加します。 –