/* * File: employee3.c * Creator: George Ferguson * * Third version of a type representing employees. * Includes memory management. */ #include #include #include // This function is in the C standard library but so what char* strdup(const char* s) { char *t = (char*)malloc(strlen(s)+1); strcpy(t, s); return t; } struct Employee { char* name; int id; }; struct Employee* new_Employee(char *name, int id) { struct Employee* this = (struct Employee*)malloc(sizeof(struct Employee)); if (this == NULL) { return NULL; // Out of memory... } this->name = strdup(name); // See text this->id = id; return this; } void Employee_print(struct Employee* this) { printf("Employee[%s,%d]", this->name, this->id); } char* Employee_get_name(struct Employee* this) { return strdup(this->name); } void Employee_set_name(struct Employee* this, char *name) { this->name = name; // See text } int Employee_get_id(struct Employee* this) { return this->id; } void Employee_set_id(struct Employee* this, int id) { this->id = id; } void Employee_free(struct Employee *this) { free(this->name); free(this); } int main(int argc, char* argv[]) { struct Employee* e1 = new_Employee("Alan Turing", 123); printf("freeing "); Employee_print(e1); printf(" ...\n"); Employee_free(e1); }