2017-10-10 44 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