学生番号と氏名をファイルから読み込み,ハッシュテーブルに登録するプログラムを作っています.
現在,次のようなところまで書いています.テーブルの内容を表示しようとしてもなかなかうまくいかないのですが,まず,構造体の定義はこれで大丈夫でしょうか.
キーは名前でデータは学生番号です.
txt
1F1601 田中萌 2F1602 木山大樹 3F1603 古味翔子
c
1#include <stdio.h> 2#include<stdlib.h> 3#include<string.h> 4 5typedef char KEY; 6typedef char DATA; 7 8 9#define SIZE 50 10#define NUM 256 11 12typedef struct cell { 13 KEY key; 14 DATA data; 15 struct cell *next; 16}CELL; 17 18CELL *table[SIZE]; 19 20void init() { 21 for (int i = 0; i < SIZE; i++) { 22 table[i] = NULL; 23 } 24} 25 26 27int hash(KEY*p) { 28 int i = 0; 29 while (*p != '\0') { 30 i += *p++; 31 } 32 return abs(i % SIZE); 33} 34 35int keyequal(KEY*a, KEY*b) { 36 if (hash(a) - hash(b) == 0) return 1; 37 return 0; 38} 39 40DATA *search_cell(KEY*key) { 41 CELL *p; 42 for (p = table[hash(key)]; p != NULL; p = p->next) { 43 if (keyequal(key, &p->key)) { 44 return &p->data; 45 46 } 47 } 48 return NULL; 49} 50 51 52 53int insert_cell(KEY*key, DATA *data) { 54 CELL *p; 55 int h; 56 if (search_cell(key) != NULL)return 0; 57 if ((p = (CELL*)malloc(sizeof(CELL))) == NULL) 58 { 59 printf("Error\n"); 60 exit(2); 61 } 62 h = hash(key); 63 p->key = *key; 64 p->next = table[h]; 65 table[h] = p; 66 return 1; 67 68 return 1; 69} 70 71 72 73int main() { 74 int i; 75 int str; 76 FILE*fp; 77 fp = fopen("J16meibo.txt", "r"); 78 KEY key[NUM]; 79 DATA data[NUM]; 80 81 for (i = 0;; i++) { 82 str = fscanf(fp, "%s %s", data, key); 83 if (str == EOF)break; 84 insert_cell(key, data); 85 } 86 return 0; 87}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。