如何将值传递给结构变量我试图从用户获取员工信息,然后将其写入文件中,但输入员工姓名后我得到segmentation fault
。 这是我的代码。如何将值传递给结构变量,然后将结构写入文件?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct record_em{
int id;
char name[20];
int salary;
int age;
};
int main(void)
{
struct record_em employee;
FILE *fp;
int id, salary, age;
char name[20];
int n=1;
fp = fopen("empRecord.dat","a");
while(n==1){
printf("\nEnter Employee ID\n");
scanf("%d",&id);
employee.id=id;
printf("\nEnter Employee Name\n");
scanf("%s",name);
employee.name=name;
printf("\nEnter Employee Salary\n");
scanf("%d",&salary);
employee.salary=salary;
printf("\nEnter Employee Age\n");
scanf("%d",&age);
employee.age=age;
fwrite(&employee,sizeof(employee),1,fp);
printf("Enter 1 to add new record \n");
scanf("%d",&n);
}
fclose(fp);
return 0;
}
输出(从评论拍摄):
Fatmahs-MacBook-Air:~ fatmah$ gcc -o em em.c Fatmahs-MacBook-Air:~ fatmah$ ./em Enter Employee ID 88 Enter Employee Name uu Segmentation fault: 11
我不明白,因为这不应该请编译如何发生分段错误:'employee.name =名称;'。这是_exact_代码吗? – hmjd
是,'Fatmahs-的MacBook空中:〜fatmah $ gcc的-o EM em.c Fatmahs-的MacBook空中:〜fatmah $ ./em 输入员工ID 输入员工姓名 UU 分段故障:11' – fatimah
请参阅http://ideone.com/3JvSwG for _error:assignment_编译器失败消息中的不兼容类型。 – hmjd