我无法找出段错误的原因。我已经在 GDB 中进行了调试,它告诉我给我带来麻烦的行,但我仍然无法弄清楚。
Employee* readfile(FILE* file) {
Employee* newemployee;
char* tempsalary;
int salary;
char* name;
char* dept;
char line[128];
while(file != NULL) {
fgets(name, sizeof(line), file);
newemployee->name = strdup(name); // THIS IS WHERE THE SEGFAULT IS
fgets(dept, sizeof(line), file);
newemployee->department = strdup(dept);
fgets(tempsalary, sizeof(line), file);
sscanf(tempsalary, "%d", &salary);
newemployee->salary = salary;
}
return newemployee;
我试图在其中运行它的主程序应该打开文件,读取行并从中创建一个 Employee 结构。它使用先前的函数打印结构。
int main() {
FILE* file;
file = fopen ("stest2.txt", "r");
Employee* employees[max_employees];
int i;
int c;
for (i = 0; i < max_employees; i++) {
employees[i] = readfile(file);
printEmployee(employees[i]);
}
}