C编程结构运行时错误

时间:2015-05-06 01:38:23

标签: c arrays struct

在createStructs()中注释掉的行给出了我的错误。我试图扫描文本文件中的信息列表,并在加载文件后给我一个程序崩溃。当它崩溃时它会输出输出,但是非常奇怪。这是我的代码:

#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 个答案:

答案 0 :(得分:1)

您的问题是您正在创建一个整数数组(int zipcode[5])。然后,您尝试传递inworkers[i].zipcode atoi电话的结果。这会导致您为整数指针分配一个整数值。

如果您在编译时没有收到警告,我会感到非常惊讶。您真的应该使用-Wall进行编译,并作为第一步解决所有警告。

不是创建这个是整数数组,为什么不让它成为整数值呢?