分段错误,结构数组

时间:2014-07-13 04:00:00

标签: c segmentation-fault structure

在构建结构数组时,我在分段错误方面遇到了很多麻烦。早些时候,我有一个程序有一个不正确的计数器,并保持分段错误,但我能够解决它。有了这个程序,我似乎无法弄清楚为什么它继续分段错误。正在读取的文件的输入是

Anthony,Huerta,24
Troy,Bradley,56
Edward,stokely,23

我想读取这个文件,对它进行标记,获取每个标记并将其存储在结构数组中的自己的结构中,所以最后我可以像在数组中那样打印结构的每个元素。例如,我希望array [0]是具有名字,姓氏和年龄的结构这是我的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct info {
    char first[20];
    char last[20];
    int age;
};

int tokenize(struct info array[],FILE* in);

int main()
{
    struct info struct_array[100];
    FILE* fp = fopen("t2q5.csv","r");
    int size = tokenize(struct_array,fp);
    int z;
    for(z=0; z < size; z++)
        printf("%s %s %d",struct_array[z].first,struct_array[z].last,struct_array[z].age);
}

int tokenize(struct info array[],FILE* in)
{
    char buffer[20];
    char* token;
    char* first_name;
    char* last_name;
    char* age;
    char* del = ",";
    int number,count,index = 0; 

    while(fgets(buffer,sizeof(buffer),in) != NULL)
    {
        token = strtok(buffer,del);
        first_name = token;
        count = 1;
        while(token != NULL)
        {
            token = strtok(NULL,del);
            if(count = 1)
                last_name = token;
            if(count = 2)
                age = token;
            count = count + 1;
        }
        number = atoi(age);
        strcpy(array[index].first,first_name);
        strcpy(array[index].last,last_name);
        array[index].age = number;
        index = index + 1;
    }
    return index;
}
抱歉,如果它是一个小错误,我倾向于想念他们但我试图找到索引问题或类似的东西,但我似乎无法发现它

2 个答案:

答案 0 :(得分:0)

执行相等性检查时会发生错误。对于if(count = 1)if(count == 1)应为count = 2,同样为=。请注意,==用于分配,{{1}}用于比较。

答案 1 :(得分:0)

if(count = 1)if(count = 2)中,使用=运算符代替==运算符。这里条件if(count = 1)if(count = 2)总是导致始终为真。因为它试图分别将1分配给变量count2变量count。最后,这两个if条件分别类似于if(1)if(2)。当if语句对所有非零值都为TRUE时,条件都会变为真并且一直执行。

为了避免这种类型的编码错误,总是将左侧的常量保持为常数并且在逻辑相等的条件下将其置于右侧,如if(1 == count)。如果错误地使用=,则会产生编译错误,因为无法分配常量。

相关问题