This is a follow up post on my last blog update Pointers in C - an eye opener. The program touches on the following -
1. Using struct as Employee record
2. Using pointer to Employee* as an employee list
3. Using void pointer and casting it to an appropriate type to avoid duplicate code
4. Allocating memory and freeing memory
struct Person { char *name; size_t age; }; typedef struct Person Employee; struct Organization { Employee **emplist; }; typedef struct Organization Org;
A sample execution of the program should be as shown:
The complete Program:
//File: StructExample.c #include <stdio.h> const size_t max_name_length = 100; size_t num_of_employees = 5; struct Person { char *name; size_t age; }; typedef struct Person Employee; struct Organization { Employee **emplist; }; typedef struct Organization Org; void* allocate_memory(size_t size) { void *ptr = (void *) malloc (size); if(NULL == ptr) { printf("\nERROR: Not enough memory"); exit(-1); } return ptr; } Employee* get_new_employee() { Employee *emp = (Employee*) allocate_memory(sizeof(Employee)); return emp; } char* get_employee_name() { char *str = (char*) allocate_memory(max_name_length); printf("Enter Employee Name: "); scanf("%s", str); return str; } size_t get_employee_age() { size_t age; printf(" Enter Employee Age: "); scanf("%u", &age); return age; } Employee* get_employee() { Employee *emp = get_new_employee(); emp->name = get_employee_name(); emp->age = get_employee_age(); return emp; } void print_employee(Employee *emp) { printf("\n[Name]: %s", emp->name); printf("\n[Age] : %d", emp->age); } size_t get_employee_count() { size_t empcount; printf("\nEnter Number of Employees: "); scanf("%u", &empcount); return empcount; } void get_org_employees(Org *org) { size_t i; org->emplist = (Employee **) allocate_memory(sizeof(Employee) * num_of_employees); for(i = 0; i < num_of_employees; i++) { org->emplist[i] = get_employee(); } } Org* get_new_org() { Org* org = allocate_memory(sizeof(struct Organization)); num_of_employees = get_employee_count(); get_org_employees(org); return org; } void print_org(Org *org) { size_t i; printf("\n[ORGANIZATION]"); for(i = 0; i < num_of_employees; i++) { print_employee(org->emplist[i]); } } void delete_employee(Employee *emp) { free(emp); emp = NULL; } void delete_org(Org *org) { size_t i; for(i = 0; i < num_of_employees; i++) { delete_employee(org->emplist[i]); } free(org); org = NULL; } int main() { Org *org = get_new_org(); print_org(org); delete_org(org); return 0; }
No comments :
Post a Comment