【发布时间】:2021-01-15 20:46:20
【问题描述】:
在过去的 2 天里,我无法完成此代码。我正在尝试实现一个哈希表。它只包含一个结构指针变量start,它存储一个结构对象。我已经声明了一个包含 26 个 Hashtable 对象的数组来存储一个结构。通过标识val的首字母来存储结构体,这是一个struct成员。
如果是val="ascii",则将其存储在ht[0]。如果val="struct",则存储在ht[18]。
我正在插入 5 个值。如果值已经存在于哈希表中,则它会打印哈希表中的值。否则,它会插入该值。我的程序无需重新分配即可正常工作。当重新分配发生时,哈希表中的值不会显示出来。查看代码下方的输出。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct List {
char val[20];
};
struct Hashtable {
struct List *start;
};
struct Hashtable ht[26];
void init();
void insert(struct List *);
void init() {
register int j;
for (j = 0; j < 26; j++) {
ht[j].start=NULL;
}
}
int main(void) {
init();
int i = 0;
int size = 5; //size = 2 reallocation occurs
struct List *newnode = (struct List*)malloc(size * sizeof(struct List));
for (i = 0; i < 5; i++) {
if (size <= i) {
size = size * size;
struct List *temp = (struct List *)realloc(newnode, size * sizeof(*temp));
if (temp == NULL) {
printf("Realloc failed\n");
} else {
printf("realoocated\n");
newnode = temp;
}
}
scanf("%s", newnode[i].val);
insert(&newnode[i]);
}
printf("Printing\n");
for (i = 0; i < 5; i++) {
printf("%s\n", newnode[i].val);
}
free(newnode);
return 0;
}
void insert(struct List *node) {
if (ht[node->val[0] - 97].start == NULL) {
ht[node->val[0] - 97].start = node;
return;
} else {
printf("The value is %s\n", ht[node->val[0] - 97].start->val);
}
}
重新分配的输出:
struct
sample
The value is struct
realoocated
string
The value is
ascii
realoocated
alpha
The value is ascii
Printing
struct
sample
string
ascii
alpha
没有重新分配的输出
struct
sample
The value is struct
string
The value is struct
ascii
alpha
The value is ascii
Printing
struct
sample
string
ascii
alpha
【问题讨论】:
-
这里有很多误解,一旦你开始工作,你可以做一些代码审查。现在,只需使用您最喜欢的调试器单步执行代码,看看哪里出错了?其他任何人都很难重现这种与您输入相同输入的情况。
-
欢迎来到stackoverflow! @Lundin 所说的,也(详细说明)请阅读有关生成 MWE 的文档:stackoverflow.com/help/minimal-reproducible-example
-
欢迎来到 Stack Overflow!为了给您一个很好的答案,如果您还没有看过How to Ask,它可能会对我们有所帮助。如果您可以提供minimal reproducible example,它可能也很有用。
标签: c data-structures struct malloc realloc