0

リンクリストチェーンを使用してハッシュテーブルを実装しようとしています。以下のコードは機能します-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define TABSIZ 200

struct record {
    struct record *next;
    char name[BUFSIZ];
    int data;
};

static struct record *htable[TABSIZ];

unsigned hash(char *s)
{
    unsigned h;

    for (h = 0; *s; s++)
        h = *s;
//printf("%d", h%TABSIZ);
//I know its not a good hash function but i wanted to check chaining
    return h % TABSIZ;
}

struct record *find(char *name)
{
    struct record *item;

    for (item = htable[hash(name)]; item; item = item->next)
    {
        if (strcmp(name, item->name) == 0)
            return item;
    }

    return NULL;
}

struct record *insert(char *name,int value)
{
    struct record *item;
    unsigned h;

    if ((item = find(name)) == NULL)
    {
        if ((item = malloc(sizeof (*item))) == NULL)
            return NULL;

        strcpy(item->name, name);
        item->data=value;
        h = hash(name);
        item->next = htable[h];
        htable[h] = item;
    }

    return item;
}
void printTable()
{
    int i=0;
    struct record *temp;
    for(i=0;i<=TABSIZ;i++)
    {
        temp=htable[i];
        while(temp!=NULL)
        {
            printf("\n%d - %s - %d\n", i,temp->name, temp->data);
            temp=temp->next;
            }
    }
}
int main(void)
{
    char buf[BUFSIZ];int value;
    struct record *item;
    do{
    printf("Enter the name of the student:\n");
    scanf("%s", buf);
    if(strcmp(buf,"stop")==0) break;
    printf("Enter the marks of the student:\n");
    scanf("%d", &value);
    if(insert(buf, value)==NULL)
    {
        break;
    }
}while((strcmp(buf,"stop"))!=0);

    printf("Enter a name to find: ");
    scanf("%s", buf);
    if((item=find(buf))!=NULL)
        printf("The marks of the student is %d\n", item->data);
    else printf("\n Not Found\n");
    printTable();
    return 0;
}

今、私はグローバル変数を削除し、構造体の配列にローカル変数を使用しようとしています。htableのグローバル宣言を削除し、メインで次のように宣言しました

struct record *htable[TABSIZ];

関数をに変更しました

struct record *find(struct record *htable, char *name);
struct record *insert(struct record *htable, char *name,int value);

そして私は関数を次のように呼んでいます

find(htable, name);
insert(htable,name,value);

しかし今、私のプログラムはsegfaultingです。構造体の配列を正しく渡しますか?正しく宣言しましたか。どんな助けでも大歓迎です。

4

2 に答える 2

2

私は以前の答えで間違った道を進んでいました。

グローバルの場合、自動的に0に初期化されます。

mainのスタックで宣言されている場合、初期化されません。

にを追加するmemset( htable, 0, sizeof(htable))main()、以前の動作に戻るはずです。

于 2012-04-11T21:27:26.683 に答える
0

printTable()の場合:

for(i=0;i<=TABSIZ;i++)

疑わしいようです。あなたはおそらく欲しい:

void printTable()
{
    unsigned int i;
    struct record *temp;

    for(i=0; i < TABSIZ;i++)
    {
        for (temp=htable[i]; temp!=NULL; temp=temp->next )
        {
            printf("\n%d - %s - %d\n", i,temp->name, temp->data);

        }
    }
}
于 2012-04-11T21:22:14.167 に答える