2017-10-10 76 views
0

我剛剛開始學習C,我對它仍然很陌生。 在這個程序中,我正在處理一系列結構。的結構是:結構中使用qsort()

typedef struct { 
    int day; 
    int month; 
    int year; 
} Date; 

typedef struct { 
    int serial_num; 
    char full_name[15]; 
    Date *pDate; 
} Person; 

陣列是Person *people

現在我的那些人的人,出生日期兩個數組(同一索引):

const char* names[MAX] = { "Sasson_Sassoni", "Pooh", "James_Bond", "Elvis_is_Alive", "Shilgiya", "Cleopatra", "Sissoo_VeSimmhoo" }; 

const int dates[MAX][COLS] = { 
     { 10, 1, 1988 }, 
     { 12, 12, 1948 }, 
     { 4, 12, 1970 }, 
     { 11, 11, 1890 }, 
     { 11, 11, 1948 }, 
     { 1, 10, 1213 }, 
     { 12, 11, 1948 } 
    }; 

通過使用switch case,每次用戶類型1從列表中的人(姓名和生日)是添加到列表people。然後,如果用戶鍵入3,則列表people應該按日期排序(從最舊到最新)。所以我寫了下面的兩個功能:

void sortList(Person **people, int index) { 
    qsort(*people, index, sizeof(Person), intcmp); 
} 
int intcmp(const void *a, const void *b) { 
    Person *one = (Person *)a; 
    Person *two = (Person *)b; 
    int year1 = one->pDate->year; 
    int year2 = two->pDate->year; 
    int month1 = one->pDate->month; 
    int month2 = two->pDate->month; 
    int day1 = one->pDate->day; 
    int day2 = two->pDate->day; 
    if (year1 > year2) 
     return -1; 
    else if (year2 > year1) 
     return 1; 
    if (month1 > month2) 
     return -1; 
    else if (month2 > month1) 
     return 1; 
    if (day1 > day2) 
     return -1; 
    else if (day2 > day1) 
     return 1; 
    return 0; 
} 

但每次我得到一個錯誤的時間說:

Exception thrown: read access violation. 
one->pDate was nullptr. 

任何幫助嗎? 謝謝!

編輯: 進一步說明:爲了將人員逐一插入數組,我創建了一個名爲index的變量,每次添加一個人時索引都會增加一個。所以當調用函數qsort()時,index是數組中的人數。也MAX=7, COLS=3, LEN=10。這增加了人們對陣列的功能是:

void addToList(Person **people, int *index, const char *names[MAX], const int dates[][COLS]) { 
    people[*index] = (Person *)malloc(sizeof(Person)); 
    people[*index]->serial_num = *index + 1; 
    strcpy(people[*index]->full_name, names[*index]); 
    Date *temp = (Date *)malloc(sizeof(Date)); 
    temp->day = dates[*index][0]; 
    temp->month = dates[*index][1]; 
    temp->year = dates[*index][2]; 
    people[*index]->pDate = temp; 
    printf("%d %s  %d/%d/%d \n", people[*index]->serial_num, people[*index]->full_name, people[*index]->pDate->day, people[*index]->pDate->month, people[*index]->pDate->year); 
    *index = *index + 1; 
} 
+0

請提供[MCVE。例如'index'的價值是什麼,'people'是什麼? – Stargateur

+0

向我們展示了填充數組'people'的代碼 –

+0

對不起,添加了變量和填充'people'的函數。 – eitanmayer

回答

2

你MCVE是不完整的,但我認爲那是因爲你混淆指針和結構:

void sortList(Person **people, int index) { 
    qsort(people, index, sizeof(Person *), intcmp); 
    // or qsort(people, index, sizeof *people, intcmp); 
} 

int intcmp(const void *a, const void *b) { 
    const Person *one = *(const Person **)a; 
    const Person *two = *(const Person **)b; 
+0

哇,工作!我一直堅持這一段時間,謝謝! – eitanmayer

+0

順便說一句,很好的使用'const'而不是使用'Person * one = *(Person **)a;' – chux