【问题标题】:Segmentation Fault, Array of structures分段错误,结构数组
【发布时间】:2014-07-13 03:59:59
【问题描述】:

我在构建结构数组时遇到了很多分段错误。早些时候我有一个程序有一个不正确的计数器并不断出现分段错误,但我能够修复它。但是,使用此程序,我似乎无法弄清楚为什么它会不断出现分段错误。正在读取的文件的输入是

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;
}

对不起,如果它是一个小错误,我倾向于错过它们,但我尝试找到索引问题或类似问题,但我似乎无法发现它

【问题讨论】:

  • if(count = 1) - 这应该使用== 进行检查
  • 打开编译器警告并修复它们,这样可以避免这样的错误。 -Wall -Wextra 代表 gcc,例如。

标签: c segmentation-fault structure


【解决方案1】:

您在进行相等检查时会出现错误。 if(count = 1) 应该是 if(count == 1)count = 2 类似。请记住,= 用于分配,== 用于比较。

【讨论】:

    【解决方案2】:

    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)。如果错误地使用=,这将导致编译错误,因为不可能分配给常量。

    【讨论】:

    • 1 == count 这样的“尤达条件”有点争议。如果使用了合理的警告级别,即使您写count = 1,编译器也会发出警告。
    • “有点争议” => wikipedia
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 2013-05-06
    • 2018-10-17
    • 2021-06-09
    相关资源
    最近更新 更多