Keep getting segmentation fault error with this C code , putting an & before output somehow resulted with the right values but again ended up with a segmentation issue, using calloc instead results in null values. I can definitely go for the approach with allocating memeory in the main() itself but tried felt like this should also work, question attached:
Make a structure with (i) Name of the employee (ii) Date of birth which is a collection of {day, month, year} (iii) Address which is a collection of {house number, zip code and state}. Write a 'C' program to read and display the data of N employees using pointers to array of structures
#include<stdio.h>
#include<stdlib.h>
typedef struct Dob{
int day;
int month;
int year;
}dob;
typedef struct Address{
int h_num;
int zip;
char* state;
}address;
typedef struct employee{
char* name;
dob date;
address ad;
}emp;
void enterEmp(emp* e,int i){
e[i].name = malloc(30*sizeof(char*));
printf("Enter name : ");
scanf("%s",e[i].name);
printf("Enter dob in dd/mm/yy format : ");
scanf("%d %d %d",&e[i].date.day,&e[i].date.month,&e[i].date.year);
printf("Enter house number and zip code : ");
scanf("%d %d",&e[i].ad.h_num,&e[i].ad.zip);
printf("Enter state : ");
e[i].ad.state = malloc(20*sizeof(char*));
scanf("%s",e[i].ad.state);
printf("\n Name : %s Date: %d/%d/%d Address- h-no: %d zip: %d state: %s \n",e[i].name,e[i].date.day,e[i].date.month,e[i].date.year,e[i].ad.h_num,e[i].ad.zip,e[i].ad.state);
}
void printEmp(emp *e,int len){
int i;
for(i=0;i<len;i++){
printf("\n Name : %s Date: %d/%d/%d Address- h-no: %d zip: %d state: %s \n",e[i].name,&e[i].date.day,&e[i].date.month,&e[i].date.year,&e[i].ad.h_num,&e[i].ad.zip,e[i].ad.state);
}
}
int main(){
int choice;
int len = 0;
do{
printf("\nEnter choice (1)Enter Employee (2)Read Employee (3)Exit : ");
emp* e = malloc(10*sizeof(emp));
scanf("%d",&choice);
switch(choice){
case 1:
enterEmp(e,len);
len++;
break;
case 2:
printEmp(e,len);
break;
case 3:
exit(0);
break;
default:
printf("Invalid Input");
break;
}
}while(1);
return 0;
}