在C中的Ubuntu上获取“分段错误(核心已转储)”以获取哈希表

时间:2018-10-10 19:55:12

标签: c segmentation-fault hashtable

我正在尝试在C语言中实现哈希表。我有一个csv文件,该文件仅包含一个姓氏列表,每个姓氏在单独的行上。例如

Sybott
尼尔·奥尼尔 波特

我要阅读的

。然后,我使用一个称为hash1的哈希函数将这些字符串转换为整数,这将为我的哈希表提供索引。然后,我要存储每个名称的出现频率。 但是,我得到的细分错误来自我的

void insert(struct individual *p)

功能。我对如何解决这个问题一无所知,只是开始练习C。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define maxSize 500

/* Hash function that returns my key as an integer, giving me my index */
int hash1(char *s){
    int hash = 0;
    while(*s){
        hash = hash + *s;
        s++;
    }
return hash;
}

/* Item to be stored */
struct individual{
    int frequency; /* Value to be stored */
    char name[50]; /* This is will be my key */
};

/* The hash table */ 
struct individual *hashArray[maxSize];

/* Initialising hash table */
void initArray(){
    for (int i = 0; i < maxSize; i++){
        hashArray[i]->frequency = 0;
        hashArray[i]->name[i] = 0;
    }
}

/* Function to load the names */
int next_field(FILE *f, char *buffer, int max){
    int i = 0, end = 0;
    for(;;){
        buffer[i] = fgetc(f);
        if(buffer[i] == '\n' || feof(f)){ end = 1; break; }
    }
    buffer[i] = 0;
    return end;
};

/* Loading the names into structs - Done */
void reader(FILE *f, struct individual *n){
    char buf[50];
    next_field(f, n->name, maxSize);
};

/* Adding to the hash table */
void insert(struct individual *p){
    struct individual *person =  malloc(sizeof(struct individual));
    int index = hash1(p->name) % maxSize;

    // The issue is coming from this line here:
    int primaryIndex = hash1(hashArray[index]->name) % maxSize;  


    /* Linear Probing */
    printf("Do I get to here\n");
    while(hashArray[index] != NULL){

        if(primaryIndex == index){
           hashArray[primaryIndex]->frequency++;  
        } else{
            ++index;  /* Going to next block */ 
        }
        index %= maxSize; /* Looping through the hash table */
    }
    hashArray[index] = person;
};

void display(struct individual *duine){
    printf("%s\n", duine->name);
};

int main(int argc, char *argv[]){
    FILE *list;
    struct individual in;
    //initArray();

    /* Opening file */
    if( argc < 2 ) { 
        printf("Also include csv file name.\n"); 
        return EXIT_FAILURE; 
    }

    /* Checking if file is found */
    list = fopen(argv[1], "r");
    if(!list) { 
        printf("File not found. %s\n", argv[1]); 
        return EXIT_FAILURE; 
    }

    while(!feof(list)){
        reader(list, &in);
        insert(&in);
        display(&in);
    }

    fclose(list);
    return EXIT_SUCCESS;
}

我在这里要做的是比较两个索引,一个来自结构p传递给该函数,另一个来自哈希表的索引。如果它们相同,则希望将存储在其中的频率计数增加1。如果我确实删除了这一行,则其余代码将正常运行。

非常感谢您

0 个答案:

没有答案