C语言 Function SegFault with Arrays of Structs



我正在使用这个函数:

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

您尝试计算wordcount长数组中"this"的出现次数,但您只填满了数组的d+1插槽。其他插槽可能包含垃圾,然后访问index[ct].labelct > d可能会导致分段错误。

您很可能正在通过数组索引。 这两行并不真正匹配(从您与我们共享的代码中:

int wordcount=get_num_words(filename);
times_on_table("this",index,wordcount);

(字数我假设在filename中计算作为第一个参数传入的内容,但这似乎与您的struct table index[]无关)

因此,在 struct table index[] 中传递的参数可能与您存储到 wordcount 中的值大小不同。 我建议您将数组大小作为参数传递给store函数,并像在工作main示例中一样使用它。 例

struct table* store(char *filename,struct table index[], int structSize){
....
times_on_table("this",index,structSize); //replace b from the call in main
}

这可能与正确设置"index[d].label"有关。尝试打印 times_on_table() 函数之外的所有标签,而不将它们与任何内容进行比较。

最新更新