2013-02-17 82 views
0

我有一個簡單的結構稱爲條目定義其中包含名稱和年齡。給定這些結構的數組,我想根據年齡對數組進行排序。指針的結構和功能

下面是我嘗試應用這個,目前我甚至無法得到這個編譯。我認爲我的指針邏輯在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; 
} 
+0

您可以用'qsort'?這會容易很多。 – nneonneo 2013-02-17 00:15:56

+0

主要目標不是排序本身,更多的是要弄清楚如何正確使用指針。 – user1895961 2013-02-18 17:15:07

回答

2

您傳遞struct entry對象的指針數組:struct entry *dict,但是你對待它,因爲它是一個指針數組來struct entry對象:(*dict[i]).age

(dict+i)仍然只是一個指向內存的指針,其中i+1。元素被存儲,即&dict[i]。要實際訪問索引爲i的此元素,您需要使用dereference operator*(dict + i),它等於dict[i]

並且還請注意,您在ij處交換元素是錯誤的。 「臨時支架」 tmp應該是一個對象,將暫時保存數據,而不是僅僅指向內存的指針,那你要重寫,從而宣告它作爲struct entry tmp;

struct entry tmp; 

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; 
     } 
    } 
} 

通過在你的代碼的方式張貼,您的if的結尾大括號(})缺失。

1

嘗試:

#include <stdio.h> 

struct entry { 
    char name[15]; 
    int age; 
}; 

void entrySort(struct entry *dict, int); 

void entrySort(struct entry *dict, int ct){ 
    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)){ /* no * */ 
      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, ct); 

    for(i = 0; i < ct; i++) 
     printf("name: %s. Age: %d\n", reg[i].name, reg[i].age); 

    return 0; 
} 
1

爲了完整起見,這裏是你如何與qsort做到這一點:

#include <stdlib.h> 
int sort_entry(const void *va, const void *vb) { 
    const struct entry *a = va; 
    const struct entry *b = vb; 
    if(a->age < b->age) return -1; 
    else if(a->age == b->age) return 0; 
    return 1; 
} 

... 

qsort(reg, ct, sizeof(struct entry), sort_entry);