我正在尝试为元素哈希表[TABLE_SIZE]分配输入文本文件。所以我用了strcpy函数。但是它没有复制到数组中。
我尝试使用malloc制作数组以便写入数组。但这没有用,所以我做了一个element *类型的变量指向hash_table数组,但是还是没用。
//this is the header file
typedef struct {
char key[100];
char data[100];
} element;
element hash_table[TABLE_SIZE];
// For caomparison count
int num_comparison;
// 파일에서 단어들을 읽어 해시테이블 구성
int build_dictionary(char *fname);
int build_dictionary(char *fname) {
int i = 0; // num of data
char key[100], data[200];
FILE *ifp;
//pointing to the hash_table array
element* hash_table_p = hash_table;
hash_table_p = (element*)malloc(sizeof(element));
//file opening error
if ((ifp = fopen(fname, "r")) == NULL) {
printf("No such file ! \n");
exit(1);
}
while (fscanf(ifp, "%s %s", key, data) == 2) {
// (key data) assigning to array
//i've tried this because hash_table[i].data didn't work
strcpy(hash_table_p->data, data);
strcpy(hash_table_p->key, key);
strcpy(hash_table[i].data, hash_table_p->data);
strcpy(hash_table[i].key, hash_table_p->key);
i++;
//checking if it is well done
printf(" %s %s \n", hash_table_p->key, hash_table_p->data);
printf(" %d %s %s \n",i , hash_table[i].data, hash_table[i].key );
}
fclose(ifp);
return(i);
}
//the input text file went as below
one 하나
two 둘
three 셋
four 넷
five 다섯
当我执行build_dictionary函数时,只有一个具有hash_table_p strcpy的函数得到了很好的分配,而hash_table中没有任何内容。
答案 0 :(得分:1)
element* hash_table_p = hash_table;
hash_table_p = (element*)malloc(sizeof(element));
您正在重写第一个作业(在致电hash_table_p
时为malloc
分配新空间),据我所知,您已经定义了表格的大小,因此您不需要保留更多空间(用malloc
删除行),并在每次迭代中增加指针的位置(就像您已经做的那样)。