【发布时间】: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