[英]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.