c/c++语言开发共享防止添加重复条目(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()的免费精选名字大全,但不是价值。 我不知道这是否是故意的。

      以上就是c/c++开发分享防止添加重复条目(C程序)相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/523259.html

      (0)
      上一篇 2020年12月11日
      下一篇 2020年12月11日

      精彩推荐