我使用这个功能:对于结构的阵列功能段错误
int times_on_table(char *search,struct table index[],int wct){
int ct=0,num=0;
while(ct<wct){
if(strcmp(search,(index[ct].label))==0) {
num++;
}
ct++;
}
return num;
}
通过结构数组搜索和查找某个字符串存储阵列中的所有时间和返回的字符串次数发生。每当我在主内使用此功能:
/*EDIT: i had a main from the wrong program my apologies*/
int main(int argc, char **argv){
int numwds=get_num_words(argv[1]);
struct table index[numwds];
int a;
struct cmd_ops symbol[22];
store(argv[1],index,numwds);
ops_gen(symbol);
int b=times_on_table("in",index,numwds);
printf("%d",b);
}
该代码工作正常。然而,当我尝试使用某些功能里面像这样的
struct table* store(char *filename,struct table index[]) {
FILE *fp;
fp=fopen(filename,"r");
char *a;int d=0,e=0,t=0;
a=malloc(60);
int wordcount=get_num_words(filename);
while(d<wordcount){
fscanf(fp,"%s",a);
if ((index[d].label=strdup(a))==NULL)
break;
index[d].word_num=d;
times_on_table("this",index,wordcount);/*when i comment this out
of my code it runs fine*/
index[d].address=findline(filename,index[d].label,wordcount,index,t);
d++;
}
free(a);
}
代码不运行,并给了我一个分段错误。有什么想法吗?
编辑:我不知道这是否有帮助,但是当我得到段错误时,它甚至在执行main中的第一行代码之前发生。
编辑:这是导致当times_on_table()被调用段错误的其他功能:
int findline(char *filename,char *check,int wordcount,struct table index[],int t){
char *a;
a=malloc(60);
int b=line_count(filename);
int ch;
fpos_t pos;
int line=0,wd=0,loc,s=0,c=1,times;
times=times_on_table(check,index,wordcount);
FILE *fp;
fp=fopen(filename,"r");
int list[wordcount];
while(c<=b){
fscanf(fp,"%s",a);
fgetpos(fp,&pos);
ch=fgetc(fp);ch=fgetc(fp);
if(strcmp(a,check)==0){
if(times==0)
return line;
else
times--;
}
if(ch==10){
line++;c++;
}
else
fsetpos(fp,&pos);
}
return line;
}
正是在此功能,我第一次加入times_on_table(),并已分段错误让我的计划从跑步。
我的想法是,你应该在调试器中运行它,以找到给出seg-fault的确切代码行。 – 2012-04-24 18:17:11
然后,您可以检查当时各种变量的值,以确定它为何出现故障。然后,您可以反向查找问题。 – 2012-04-24 18:17:48
你有没有试过valgrind? – 2012-04-24 18:18:29