C标记并分析csv文件

时间:2017-09-27 19:36:32

标签: c struct io token

我正在学习如何使用令牌来分析文件并将其放在struct数组中。我的代码编译得很好,但在运行时崩溃了。有人可以帮忙吗?

这是我的代码:

struct state_info {
    char code[3];
    unsigned long num_records;
    unsigned long total_income;
    unsigned long total_vehicles;
    unsigned long total_population;
    unsigned long total_rent;
    unsigned long total_renter;
};

int main(int argc, char *argv[]) {
    const int num_states = 100;
    struct state_info *states[num_states];
    FILE *file = fopen(argv[i], "r");
    analyze_file(file, states, num_states);
}

void analyze_file(FILE *file, struct state_info *states[], int num_states) {
    const int line_sz = 100;
    char line[line_sz];
    while (fgets(line, line_sz, file) != NULL) {
        char* token = strtok(line, " \n");
        while(token != NULL) {
            //allocate memory
            int size = atoi(token);
            if(states[size] == NULL) {
                states[size] = malloc(sizeof(struct state_info));
                states[size]->num_records = 0;
                states[size]->total_income = 0;
                states[size]->total_vehicles = 0;
                states[size]->total_population = 0;
                states[size]->total_rent = 0;
                states[size]->total_renter = 0;
            }
            //add value to the states
            token = strtok(NULL, " \n");
            strcpy(states[size]->code, token);
            token = strtok(NULL, " \n");
            states[size]->total_population += atoi(token);
            token = strtok(NULL, " \n");
            states[size]->total_income += atoi(token);
            token = strtok(NULL, " \n");
            states[size]->total_vehicles += atoi(token);
            token = strtok(NULL, " \n");

            //calculate total rent and total renter
            if(atoi(token) != 0) {
                states[size]->total_rent += atoi(token);
                states[size]->total_renter++;
            }
        }
        states[size]->num_records++;
        token = strtok(NULL, " \n");
    }
}

我认为我的指针应该有问题,但我不确定。

1 个答案:

答案 0 :(得分:0)

语句struct state_info *states[num_states]不会使用NULL - 值初始化指针数组,因此它可能包含" garbage" (即指针!= NULL指向不是有效对象的东西)。

因此,像if(states[size] == NULL)这样的比较可能永远不会评估为真,因此永远不会分配适当的对象。对states[size]的后续访问将导致未定义的行为(实际上访问states[size]==...已经是未定义的行为,但我敢打赌"崩溃"是由于后续访问)

也许还有其他问题;但我认为这是你代码中最明显的事情。

通过初始化states来解决此问题,例如struct state_info *states[num_states] = { NULL }