방금 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
입니다.
가 지금은 그 사람의 사람과 생년월일의 두 배열 (동일 색인)이 있습니다 switch case
를 사용하여
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 }
};
를 모든 시간은 사용자가 입력 한 목록에서 사람 (이름과 생일)입니다 목록에 추가 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.
어떤 도움을? 감사합니다.
EDIT : 추가 설명 : 사람을 배열에 하나씩 삽입하려면 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;
}
는 [mcve]을 제공하세요. 예를 들어'index'의 값은 무엇입니까,'people'은 무엇입니까? – Stargateur
배열'people'을 채우는 코드를 보여줍니다. –
죄송합니다.'people'을 채우는 변수와 함수를 추가했습니다. – eitanmayer