seg fault in array of structs

I get a seg fault after I enter the Years of Employment. Could anyone tell me why? thanks a lot in advance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>
#include <stdlib.h>

#define COMPANY_NUM_EMPL 6
#define NAME_LENGTH 20


typedef struct {
	char first_name[20];
	char last_name[20];
	int years_of_empl;
	float salary;
}Employee;


/*typedef struct {
	Employee *empl;
}Company;
*/

int main(){

	int i;
	Employee *empl=calloc(COMPANY_NUM_EMPL,sizeof(*empl));
	
	
	/*for (i=0;i<COMPANY_NUM_EMPL;i++){
		
		empl[i].first_name=calloc(NAME_LENGTH,sizeof(char));
		empl[i].last_name=calloc(NAME_LENGTH,sizeof(char));
		
		
	}*/
	
	for (i=0;i<COMPANY_NUM_EMPL;i++){
		printf("Enter First Name\n");
		scanf("%s",empl[i].first_name);
		printf("%s\n",empl[i].first_name);
		printf("Enter Last Name\n");
		scanf("%s",empl[i].last_name);
		printf("Enter Years of Employment\n");
		scanf("%d",empl[i].years_of_empl);
		printf("Enter Salary\n");
		scanf("%f",empl[i].salary);
		
		printf("%s\n%s\n%d\n%f",empl[i].first_name, empl[i].last_name, empl[i].years_of_empl, empl[i].salary);
	}
	
	return 0;
}
sorry, just noticed the & is missing in scanf
Hi,
The issue is due to the improper usage of calloc function.Actually calloc returns a (void*) so you have to typecast to (Employee*) before assigning, like this
Employee *empl = (Employee*)calloc(COMPANY_NUM_EMPL,sizeof(*empl));
Topic archived. No new replies allowed.