C:将元素插入结构数组

标签 c struct insert hashtable

我有一个结构数组,其中每个数组元素是:

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/

相关文章:

无法解决如何将函数作为参数传递

c - 使用 fscanf 读取 C 中的坐标时出现问题

转换结构指针

c++ - 如何声明一个 std::array of structs initialized inline with different values

mysql - SQL表一次又一次接受相同的名称数据库名称检查

c++ - 使用#pragma detect_mismatch 确保 DLL 使用正确的静态链接库

c - 带有指向 const 数据的目标指针的 memcpy

ios - Metal 数据类型对应的 Swift 数据类型?

python - 根据条件在嵌套列表中插入缺失元素 - Python

MySQL插入查询错误代码: 1406.列数据太长