Advertisement
Guest User

yas

a guest
Feb 21st, 2019
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct emp
  5. {
  6. int ID;
  7. float salary;
  8. int age;
  9. }Employee;
  10.  
  11. Employee ** createEmployeeArray(int);
  12. int addNewEmployee(Employee *, Employee **);
  13. void * freeEmployeeArray(Employee **);
  14.  
  15. int main(void){
  16. //int length;
  17.  
  18. //FILE *fp;
  19.  
  20. //fp = fopen("filename", "r");
  21.  
  22. //fscanf(fp,"%d\n", &length);//scan in maxLength
  23.  
  24. Employee** empArray = createEmployeeArray(10);//create array
  25.  
  26. printf("%p", empArray);
  27.  
  28. //fclose(fp);
  29.  
  30. empArray = freeEmployeeArray(empArray);//make it to where you cant reference it later accidentally
  31. return 0;
  32. }
  33. Employee ** createEmployeeArray(int maxLength){
  34. Employee ** array;
  35. array = (Employee**)malloc(sizeof(int)*2+sizeof(Employee * ) * maxLength);
  36. *((int*)array++) = maxLength;
  37. *((int*)array++) = 0;
  38. for(int i=0; i<maxLength; i++)
  39. {
  40. array[i] = (Employee*)malloc(sizeof(Employee));//make room for rest of employees
  41. }
  42. return (Employee**)array;
  43. }
  44. int addNewEmployee(Employee *p, Employee **array){
  45. int max = *((int*)array[-2]);
  46. int count = 0;
  47. while(count <= max){
  48. if(count == max){
  49. return -1;//return -1 if the array is full
  50. }
  51. else{
  52. if(array[count] == NULL){
  53. *((Employee*)array[count]) = *p;//add employee
  54. return count;//return index of added employee
  55. }
  56. }
  57. count++;//increment index variable
  58. }
  59. return -2;//return -2 if adding of employee fails
  60. }
  61. void * freeEmployeeArray(Employee **array){
  62. int size = *((int*) array - 2);
  63. for(int i = 0; i<size; i++)
  64. {
  65. free (array[i]);//free the entire array
  66. }
  67. array = (Employee**)((int*) array - 2);
  68. free(array);
  69. return NULL;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement