Note that there are some explanatory texts on larger screens.

plurals
  1. POTrying to read data from a text file, make a struct from it, and print the fields to stdout
    primarykey
    data
    text
    <p>I seem to have no problems reading from the file and then creating the struct, but printing the struct gives me a segmentation fault.</p> <p>Employee definition</p> <pre><code>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; </code></pre> <p>Function to read from a file</p> <pre><code>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-&gt;name = strdup(status); fgets(tempsalary, sizeof(name), file); sscanf(tempsalary, "%d", &amp;salary); newemployee-&gt;salary = salary; fgets(depts, sizeof(dept), file); newemployee-&gt;department = strdup(depts); return newemployee; } } </code></pre> <p>Function to print the struct generated by readfile.</p> <pre><code>void printEmployee(Employee *employee) { fprintf(stdout, "Name = %sSalary = %d\nDepartment = %s\n\n", // SEGFAULT HERE employee-&gt;name, employee-&gt;salary, employee-&gt;department); } </code></pre> <p>Main program</p> <pre><code>int main() { FILE* file; file = fopen ("stest2.txt", "r"); Employee* employees[max_employees]; int i; int c; Employee* temp; for (i = 0; i &lt; max_employees; i++) { employees[i] = readfile(file) printEmployee(employees[i]); } return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload