Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef struct emp
- {
- int ID;
- float salary;
- int age;
- }Employee;
- Employee ** createEmployeeArray(int);
- int addNewEmployee(Employee *, Employee **);
- void * freeEmployeeArray(Employee **);
- int main(void){
- //int length;
- //FILE *fp;
- //fp = fopen("filename", "r");
- //fscanf(fp,"%d\n", &length);//scan in maxLength
- Employee** empArray = createEmployeeArray(10);//create array
- printf("%p", empArray);
- //fclose(fp);
- empArray = freeEmployeeArray(empArray);//make it to where you cant reference it later accidentally
- return 0;
- }
- Employee ** createEmployeeArray(int maxLength){
- Employee ** array;
- array = (Employee**)malloc(sizeof(int)*2+sizeof(Employee * ) * maxLength);
- *((int*)array++) = maxLength;
- *((int*)array++) = 0;
- for(int i=0; i<maxLength; i++)
- {
- array[i] = (Employee*)malloc(sizeof(Employee));//make room for rest of employees
- }
- return (Employee**)array;
- }
- int addNewEmployee(Employee *p, Employee **array){
- int max = *((int*)array[-2]);
- int count = 0;
- while(count <= max){
- if(count == max){
- return -1;//return -1 if the array is full
- }
- else{
- if(array[count] == NULL){
- *((Employee*)array[count]) = *p;//add employee
- return count;//return index of added employee
- }
- }
- count++;//increment index variable
- }
- return -2;//return -2 if adding of employee fails
- }
- void * freeEmployeeArray(Employee **array){
- int size = *((int*) array - 2);
- for(int i = 0; i<size; i++)
- {
- free (array[i]);//free the entire array
- }
- array = (Employee**)((int*) array - 2);
- free(array);
- return NULL;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement