如何將值傳遞給結構變量我試圖從用戶獲取員工信息,然後將其寫入文件中,但輸入員工姓名後我得到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