#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<string.h>
struct date {
int year;
int month;
int day;
};
struct person{
char name[64];
struct date birthday;
};
struct aop {
int max;
struct person **data;
};
struct aop *create_aop(int max) {
struct aop *new = malloc(sizeof(struct aop));
new->data = malloc(max*sizeof(struct person));
for (int i=0; i<max; i++) {
new->data[i] = NULL;
}
new->max = max;
return new;}
void destroy_aop(struct aop *a) {
free(a->data);
free(a);
}
int add_person(struct aop *a, char *name, struct date birthday) {
if (a->data[a->max-1] != NULL) {
return -1;
}
struct person *new_person = malloc(sizeof(struct person));
strcpy(new_person->name, name);
new_person->birthday = birthday;
for (int i=0; i<a->max; i++) {
if (a->data[i] == NULL) {
a->data[i] = new_person;
break;
}
}
free(new_person);
return 0;
}
내가 작성한 코드에 대해 몇 가지 질문이 있습니다. 첫째, 사람의 이름과 생일을 초기화하기 위해 create_aop에 추가 코드를 추가해야합니까? 그리고 add_person의 free (new_person) 이후에 a-> data [0] -> name에 도달 할 수 없다는 것을 알았습니다. 다른 포인터를 사용하지 않고 a-> data [i]를 어떻게 바꿀 수 있습니까?포인터에 메모리를 할당하는 방법
struct aop *birthdays(const struct aop *a, int month) {
int m = a->max;
struct aop *n = create_aop(m);
int j = 0;
for (int i=0; i<m; i++) {
if (a->data[i] != NULL) {
if (a->data[i]->birthday.month == month) {
n->data[j] = a->data[i];
j++;
}
} else {
break;
}
}
if (j == 0) {
return NULL;
}
return n;
}
위의 기능을 실행할 때마다 메모리에 오류가 있습니다. 나는 몇 시간 동안 그것에 대해 생각 해왔다.하지만 이것에 무엇이 잘못되었는지 전혀 모른다.
'새로 만들기 -> 데이터 = malloc에 (최대 *의를 sizeof (구조체 사람));'->'새로 만들기 -> 데이터 =은 calloc (최대,를 sizeof (구조체 사람 *)),'free (new_person);' – BLUEPIXY
'sizeof (struct person *)'보다'sizeof * new-> data'가 더 좋습니다. 오류가 발생하기 쉽습니다. – Deduplicator
일반적으로 'new'는 예약어입니다. 더 나은 이름을 사용하도록 제안하십시오. – user3629249