2015-05-06 88 views
0

已在createStructs()中註釋掉的行向我提供了有關的錯誤。我正在嘗試掃描來自文本文件的信息列表,並在加載文件後給我一個程序崩潰。當它崩潰時,它將輸出輸出,但是以一種非常奇怪的方式。這裏是我的代碼:C編程結構運行時錯誤

#define MAX 71 
#define SIZE 14 

typedef struct { 
    char first[7]; 
    char initial[1]; 
    char last[9]; 
    char street[16]; 
    char city[11]; 
    char state[2]; 
    int zipcode[5]; 
    int age; 
    char sex[1]; 
    int tenure; 
    double salary; 
} Employee; 
    insert main method just calling the functions 
    void strsub(char buf[], char sub[], int start, int end) { 
    int i, j = 0; 

    for (j = 0, i = start; i <= end; i++, j++) { 
     sub[j] = buf[i]; 
    } 
    sub[j] = '\0'; 
} 

void createStructs(Employee inWorkers[]) { 
    int i = 0; 
    char buf[MAX]; 
    char temp[SIZE]; 
    if (!(fp = fopen("payfile.txt", "r"))) { 
     printf("payfile.txt could not be opened for input."); 
     exit(1); 
    } 

    while (!(feof(fp))) { 
     fgets(buf, MAX, fp); 
     strsub(buf, inWorkers[i].first, 0, 6); 
     strsub(buf, inWorkers[i].initial, 8, 8); 
     strsub(buf, inWorkers[i].last, 10, 18); 
     strsub(buf, inWorkers[i].street, 20, 35); 
     strsub(buf, inWorkers[i].city, 37, 47); 
     strsub(buf, inWorkers[i].state, 49, 50); 
     strsub(buf, temp, 52, 56); 
     //inWorkers[i].zipcode = atoi(temp); 
     strsub(buf, temp, 58, 59); 
     inWorkers[i].age = atoi(temp); 
     strsub(buf, inWorkers[i].sex, 61, 61); 
     strsub(buf, temp, 63, 63); 
     inWorkers[i].tenure = atoi(temp); 
     strsub(buf, temp, 65, 70); 
     inWorkers[i].salary = atof(temp); 
     i++; 
    } 
} 

void printNames(Employee workers[]) { 
    for (int i = 0; i < SIZE; i++) { 
     printf("%s %s %s %s %s %s %d %d %s %d %.2lf", workers[i].first, workers[i].initial, workers[i].last, 
      workers[i].street, workers[i].city, workers[i].state, workers[i].zipcode, workers[i].age, 
      workers[i].sex, workers[i].tenure, workers[i].salary); 
    } 
} 
+1

將'int zipcode [5];'更改爲'int zipcode;'(除非您確實需要每位員工5個郵編)。在嘗試'fopen'之前,你還需要聲明'FILE * fp = NULL;'。並看到[**爲什麼是「while(!feof(file))」總是錯誤的?**](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) –

回答

1

你的問題是,你正在創建一個整數數組(int zipcode[5])。然後您嘗試通過inworkers[i].zipcode調用atoi的結果。結果是你將一個整數值賦給一個整數指針。

如果您在編譯時沒有收到警告,我會很驚訝。你真的應該編譯-Wall並解決所有警告作爲第一步。

而不是創建這是一個整數數組,爲什麼不只是讓它成爲一個整數值?