名前と年齢を含むエントリが定義された単純な構造があります。これらの構造の配列を前提として、年齢に基づいて配列を並べ替えたいと思います。
以下はこれを適用する私の試みですが、現時点ではこれをコンパイルすることさえできません。私のポインタロジックは、ifステートメントの比較とそれに続くポインタの交換の両方で正しくないと思います。同じことをするためにいろいろな方法を試しましたが、どこにも行きません。私はCにかなり慣れていませんが、まだポインターに頭を悩ませようとしているので、おそらくそれは私が誤解している基本的なことです。誰かが私が間違っていることを以下に説明できますか?
どんな助けでも大歓迎です。
#include <stdio.h>
struct entry {
char name[15];
int age;
};
void entrySort( struct entry *dict);
void entrySort( struct entry *dict){
int i,j; // counters
int ct = 4;
struct entry *tmp; // temporary holder
for( i = 0; i < ct; i++){
for( j = 0; j < ct; j++ ){
if ((*dict[i].age) > (*dict[j].age)){
tmp = (dict + i);
(dict+i) = (dict+j);
(dict+j) = tmp;
}
}
}
int main (void){
int ct = 4, i;
struct entry reg[4] =
{{ "John", 24 },
{ "Alan", 18 },
{ "Jim", 40 },
{ "Sarah",32 }};
entrySort(reg);
for( i = 0; i < ct; i++)
printf("name: %s. Age: %d\n", reg[i].name, reg[i].age);
return 0;
}