C 尝试从文本文件中读取数据,从中生成结构,并将字段打印到标准输出

C 尝试从文本文件中读取数据,从中生成结构,并将字段打印到标准输出,c,struct,segmentation-fault,fgets,C,Struct,Segmentation Fault,Fgets,我从文件中读取然后创建结构似乎没有问题,但是打印结构给了我一个分段错误 雇员定义 struct _Employee { int salary; // Monthly salary in UK pounds sterling char *name; // Pointer to character string holding name of employee. char* department; // MUST be dynamically allocated fr

我从文件中读取然后创建结构似乎没有问题,但是打印结构给了我一个分段错误

雇员定义

struct _Employee {
  int salary; // Monthly salary in UK pounds sterling
  char *name; // Pointer to character string holding name of employee.
  char* department;           // MUST be dynamically allocated from the heap.
};

typedef struct _Employee Employee;
函数从文件中读取

Employee* readfile(FILE* file) {
  Employee* newemployee;
  newemployee = malloc(sizeof(Employee));
  char tempsalary[10];
  int salary;
  char name[20];
  char dept[20];
  char* names = malloc(sizeof(name));
  char* depts = malloc(sizeof(dept));
  char* status; // Returned by fgets(). Will be NULL at EOF


    status = fgets(names, sizeof(name), file);
    if (status == NULL)
      return NULL;
    else {
      newemployee->name = strdup(status);


    fgets(tempsalary, sizeof(name), file);
    sscanf(tempsalary, "%d", &salary);
    newemployee->salary = salary;

    fgets(depts, sizeof(dept), file);
    newemployee->department = strdup(depts);

    return newemployee;
    }
}
函数打印readfile生成的结构

void printEmployee(Employee *employee) {
      fprintf(stdout, "Name = %sSalary = %d\nDepartment = %s\n\n", // SEGFAULT HERE
          employee->name, employee->salary, employee->department);
}
主程序

int main() {
  FILE* file;
  file = fopen ("stest2.txt", "r");
  Employee* employees[max_employees];
  int i;
  int c;
  Employee* temp;

    for (i = 0; i < max_employees; i++) {
    employees[i] = readfile(file)   
    printEmployee(employees[i]);
    }
  return 0;
}
intmain(){
文件*文件;
file=fopen(“stest2.txt”,“r”);
雇员*雇员[最多雇员];
int i;
INTC;
雇员*临时工;
对于(i=0;i
我必须在堆栈上使用fgets()涂鸦。更改此项:

 fgets(tempsalary, sizeof(name), file);
为此:

 fgets(tempsalary, sizeof(tempsalary), file);
可能不是问题,但肯定是“a”问题。

readfile()在发生fgets错误时可以返回NULL。这个案件主要不在处理之中。 作为一个原始建议:

    for (i = 0; i < max_employees; i++) {
        employees[i] = readfile(file);
        if(NULL != employees[i])
        {   
            printEmployee(employees[i]);
        }
        else
        {
            printf("Error reading file");
        }
for(i=0;i
请显示员工类型定义。我将其添加到代码顶部。仍在查看,但您告诉fgets(),tempsalary可以容纳20个字节,即使它只能容纳10个字节。好的,我已修复了该问题,但仍会出现seg错误。oleg_g FTW:即使在readfile()之后,您仍在打印员工返回null。当我在gdb中调试时,我得到以下错误:程序接收信号SIGSEGV,分段错误。printEmployee(employee=0x0)中的0x0000000000400868。如果(status==null)返回null,我应该如何在main中处理这个问题?