This program simply reads a list of employes from the user, prints it
and then destroys the allocated memory. I have a function
free_memory(voi d *ptr) which will free the memory pointed to by
pointer ptr. I included a pointer to this function in the emplist
data structure free_employee_l ist. Is this a good way to program ??
what if there are a number of such different data structures. Would it
suffice to have a single free_memory function throughout the project
and include a pointer to this function in every data structure ??
#include <stdio.h>
#include <stdlib.h>
typedef struct _employee
{
int eid;
float sal;
int age;
}employee;
typedef struct _emplist
{
int n;
employee *e;
void (*free_employee _list)();
}emplist;
void free_memory(voi d *ptr)
{
free(ptr);
printf("\nMemor y freed\n");
}
int main(void)
{
emplist *list;
int i;
list = malloc(sizeof(* list));
if(list == NULL)
{
fprintf(stderr, "memory allocation failed\n");
return 1;
}
list->free_employee_ list = free_memory;
printf("Enter number of employees\n");
scanf("%d", &list->n);
list->e = malloc(sizeof(e mployee) * list->n);
if(list->e == NULL)
{
fprintf(stderr, "memory allocation failed\n");
return 1;
}
for(i = 0; i < list->n; i++)
{
printf("Enter id, age, salary\n");
scanf("%d %d %f", &list->e[i].eid, &list->e[i].age, &list-
}
for(i = 0; i < list->n; i++)
{
printf("Employe id: %d age: %d sal: %f\n", list->e[i].eid, list-
}
list->free_employee_ list(list);
return 0;
}
and then destroys the allocated memory. I have a function
free_memory(voi d *ptr) which will free the memory pointed to by
pointer ptr. I included a pointer to this function in the emplist
data structure free_employee_l ist. Is this a good way to program ??
what if there are a number of such different data structures. Would it
suffice to have a single free_memory function throughout the project
and include a pointer to this function in every data structure ??
#include <stdio.h>
#include <stdlib.h>
typedef struct _employee
{
int eid;
float sal;
int age;
}employee;
typedef struct _emplist
{
int n;
employee *e;
void (*free_employee _list)();
}emplist;
void free_memory(voi d *ptr)
{
free(ptr);
printf("\nMemor y freed\n");
}
int main(void)
{
emplist *list;
int i;
list = malloc(sizeof(* list));
if(list == NULL)
{
fprintf(stderr, "memory allocation failed\n");
return 1;
}
list->free_employee_ list = free_memory;
printf("Enter number of employees\n");
scanf("%d", &list->n);
list->e = malloc(sizeof(e mployee) * list->n);
if(list->e == NULL)
{
fprintf(stderr, "memory allocation failed\n");
return 1;
}
for(i = 0; i < list->n; i++)
{
printf("Enter id, age, salary\n");
scanf("%d %d %f", &list->e[i].eid, &list->e[i].age, &list-
>e[i].sal);
for(i = 0; i < list->n; i++)
{
printf("Employe id: %d age: %d sal: %f\n", list->e[i].eid, list-
>e[i].age, list->e[i].sal);
list->free_employee_ list(list);
return 0;
}
Comment