P
pereges
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(void *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_list. 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(void *ptr)
{
free(ptr);
printf("\nMemory 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(employee) * 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.eid, &list->e.age, &list-
}
for(i = 0; i < list->n; i++)
{
printf("Employe id: %d age: %d sal: %f\n", list->e.eid, list-
}
list->free_employee_list(list);
return 0;
}
and then destroys the allocated memory. I have a function
free_memory(void *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_list. 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(void *ptr)
{
free(ptr);
printf("\nMemory 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(employee) * 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.eid, &list->e.age, &list-
e.sal);
}
for(i = 0; i < list->n; i++)
{
printf("Employe id: %d age: %d sal: %f\n", list->e.eid, list-
e.age, list->e.sal);
}
list->free_employee_list(list);
return 0;
}