gpt4 book ai didi

c - 带有结构数组的函数段错误

转载 作者:太空宇宙 更新时间:2023-11-04 00:09:09 24 4
gpt4 key购买 nike

我正在使用这个功能:

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

搜索一个结构体数组,查找特定字符串在数组中存储的所有时间,并返回该字符串出现的次数。每当我在 main 中使用这个函数时:

/*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(),并且段错误使我的程序无法运行。

最佳答案

这里

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

您尝试计算 "this"wordcount 长数组中的出现次数,但您只填充了 d+1 个槽位阵列。其他槽可能包含垃圾,然后在ct > d时访问index[ct].label很可能导致段错误。

关于c - 带有结构数组的函数段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10303670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com