我有一个结构数组,其中每个数组元素是:
struct Item {
int code;
char * label;
};
数组本身是一个全局变量:
struct Item * ht[SIZE];
这就是我当前将项目插入数组的方式:
void insert(int toadd, char *toput) {
struct Item *item = (struct Item*) malloc(sizeof(struct Item));
item->label = toput;
item->code = toadd;
int hashIndex = 0;
//move in array until an empty or deleted cell
while(ht[hashIndex] != NULL && ht[hashIndex]->code != -1) {
//go to next cell
++hashIndex;
//wrap around the table
hashIndex %= SIZE;
}
ht[hashIndex] = item;
}
在另一个函数中,我调用 insert 方法,然后使用一些 printf 语句来检查发生了什么:
insert(ctr, trimwhitespace(line2));
printf("\nAdding to ht: String: %s Integer: %d\n", trimwhitespace(line2), ctr);
for (int i = 0; i < SIZE; i++) {
if (ht[i] != NULL)
printf("\nThis is what's inside ht: String: %s Integer: %d\n", ht[i] -> label, ht[i] -> code);
}
这是输出示例:
添加到 ht:字符串:4 整数:6
这就是 ht 里面的内容:字符串:四整数:0
这就是 ht 里面的内容:字符串:四整数:4
这就是 ht 里面的内容:字符串:4 整数:5
这就是 ht 里面的内容:字符串:4 整数:6
正如您所看到的,该结构体被多次插入,并且具有不同的整数值。
我认为这不太可能是 insert
调用所在的循环的问题,因为如果 insert
已多次调用电话。但我可能错了。
如何确保 insert
方法仅插入结构一次而不是多次?
或者问题出在其他地方?
最佳答案
事实证明,在我的 insert
方法调用之前添加一个 if
语句来检查特定键是否已提前插入,解决了问题,尽管这可能不会是最理想的修复:
if (!containsKey(trimwhitespace(stringcopy3))) {
insert(ctr, trimwhitespace(stringcopy3));
printf("\nAdding to ht: String: %s Integer: %d\n", trimwhitespace(stringcopy3), ctr);
}
我仍然不确定为什么首先插入 key 的多个实例,但这是一个临时解决方案。
关于C:将元素插入结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52621141/