被添加preventing重复条目(C程序) [英] Preventing duplicate entry from being added (C program)

查看:126
本文介绍了被添加preventing重复条目(C程序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这增加了表中的条目的方法。这些条目名称和地址的人

I've a method which adds an entry to the table. The entries are name and addresses of people.

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 < table->currentElements;i++) {
       if(strcmp(table->array[i].name, name) == 0) {
           table->array[i].value = value;
       }
    }
  return 0;
}

不过,如果我再次通过相同名称的方法,但是传递不同的地址,它应更新旧条目用新的地址(即价值​​),但它不应该把它作为一个全新的项目。例如,

However, if I pass the same name to the method again but pass different address, it should update the address (i.e value) of the old entry with the new one BUT it shouldn't consider it as a whole new entry. For example,

如果我给一组条目 -

If I give a set of entries -

1)乔治126藤街

2),阿什利 - 889藤街

2) Ashley "889 Vine Street"

3)乔治556藤街

程序应该只更新乔治的地址(即价值​​),但不应该添加表中的另一个重复条目。

The program should just update the address of George (i.e the value) but shouldn't add another duplicate entry in the table.

我的code的问题是,我这样做是什么它给我的方式,这是 -

The problem with my code is, the way I am doing it, this is what it gives me -

---什么,我抵达---

---WHAT I AM GETTING---

1)乔治556藤街

2),阿什利 - 889藤街

2) Ashley "889 Vine Street"

3)乔治556藤街

- 预期 -

1)乔治556藤街

2),阿什利 - 889藤街

2) Ashley "889 Vine Street"

推荐答案

移动的循环的分配前:

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++;

瓦尔特

这篇关于被添加preventing重复条目(C程序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆