防止添加重复条目(C程序)
我有一个方法可以在表格中添加一个条目。 条目是人的姓名和地址。
int rtable_add(RESIZABLE_TABLE * table, char * name, void * value) { table->array[table->currentElements].name = strdup(name); table->array[table->currentElements].value = value; table->currentElements++; int i = 0; for(i = 0; i currentElements;i++) { if(strcmp(table->array[i].name, name) == 0) { table->array[i].value = value; } } return 0; }
但是,如果我再次将相同的名称传递给方法但传递不同的地址,它应该使用新的地址更新旧条目的地址(即值)但是它不应该将其视为一个完整的新条目。 例如,
如果我给出一组条目 –
1)乔治“126 Vine Street”
2)阿什利“889 Vine Street”
3)乔治“556 Vine Street”
程序应该只更新George的地址(即值),但不应在表中添加另一个重复的条目。
我的代码的问题是,我这样做的方式,这就是它给我的 –
—我得到了什么—
1)乔治“556 Vine Street”
2)阿什利“889 Vine Street”
3)乔治“556 Vine Street”
– 预期 –
1)乔治“556 Vine Street”
2)阿什利“889 Vine Street”
在赋值之前移动for循环 :
int i = 0; for(i = 0; i < table->currentElements;i++) { if(strcmp(table->array[i].name, name) == 0) { table->array[i].value = value; //change the value return 0; //dont add a new one } } table->array[table->currentElements].name = strdup(name); table->array[table->currentElements].value = value; table->currentElements++;
瓦尔特
问题是在一开始。 您首先创建一个新条目,将其添加到表中,然后修改循环中的现有条目。 我建议先搜索匹配的条目,如果没有找到任何内容,只建议添加一个。
运行代码时发生的是,创建条目#3并将其添加到表中,然后在for循环中修改条目#1。
您的代码所做的第一件事是将传递的名称和值作为数组末尾的新条目插入:
table->array[table->currentElements].name = strdup(name); table->array[table->currentElements].value = value;
接下来要做的是遍历表格,查找具有相同名称的任何项目,并将其值设置为传入的值,在您的示例中,这将更新原始条目和刚刚添加到该条目的函数。结束:
int i = 0; for(i = 0; i < table->currentElements;i++) { if(strcmp(table->array[i].name, name) == 0) { table->array[i].value = value; } }
顺便说一句,你是strdup()的名字,但不是价值。 我不知道这是否是故意的。