[英]C: Inserting element into an array of structs
我有一个结构数组,其中每个数组元素是:
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: String: 4 Integer: 6
这是 ht 里面的内容: String: 4 Integer: 0
这是 ht 里面的内容: String: 4 Integer: 4
这是 ht 里面的内容: String: 4 Integer: 5
这是 ht 里面的内容: String: 4 Integer: 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);
}
我仍然不确定为什么首先插入密钥的多个实例,但这是一个临时解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.