//
//struct
//
typedef struct _person{
char *firstName;
char *lastName;
char *title;
uint age;
}Person;
void initializePerson(Person *person,const char *fn,
const char *ln,const char *title,
uint age ) {
person ->firstName = (char *)malloc(strlen(fn)+1);
strcpy(person->firstName, fn);
person ->lastName = (char *)malloc(strlen(ln)+1);
strcpy(person->lastName, ln);
person ->title = (char *)malloc(strlen(title)+1);
strcpy(person->title, ln);
person->age = age;
}
void deallocatePerson(Person *person){
free(person->firstName);
free(person->lastName);
free(person->title);
}
void processPerson(){
// Person person;
// initializePerson(&person, "person", "Underwood", "Manage", 26);
//
// deallocatePerson(&person);
Person *ptrPerson;
ptrPerson = (Person*)malloc(sizeof(Person));
initializePerson(ptrPerson, "person", "Underwood", "Manage", 26);
//...
deallocatePerson(ptrPerson);
free(ptrPerson);
}
#define LIST_SIZE 5
Person *list[LIST_SIZE];
void initializeList(){
for (int i =0; i<LIST_SIZE;i++ ) {
list[i]= NULL;
}
}
/*
list[i] ptr
|
↓
Person
list[i] ptr
| |
↓ ↓
NULL Person
*/
Person *getPerson(){
for (int i =0; i<LIST_SIZE; i++) {
if (list[i]!=NULL) {
Person *ptr = list[i];//ptr,与list都指向Person
list[i]= NULL;
return ptr;
}
}
Person *person = (Person *)malloc(sizeof(Person));
return person;
}
Person *returnPerson(Person *person){
for (int i = 0; i< LIST_SIZE; i++) {
if (list[i]==NULL) {
list[i]= person;
return person;
}
}
deallocatePerson(person);
free(person);
return NULL;
}
int main(int argc, const char * argv[]) {
//struct
initializeList();
Person *ptrPerson;
ptrPerson = getPerson();
initializePerson(ptrPerson, "Ralph", "Fitsgerald", "Mr", 35);
returnPerson(ptrPerson);
ptrPerson = getPerson();
initializePerson(ptrPerson, "Salph", "gitsgerald", "Mr", 45);
returnPerson(ptrPerson);
ptrPerson = getPerson();
initializePerson(ptrPerson, "Talph", "hitsgerald", "Mr", 55);
returnPerson(ptrPerson);
return 0;
}