在结构数组清除的项 [英] Clearing an item in a struct array

查看:111
本文介绍了在结构数组清除的项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个问题,我问的延续这里

This is continuation of a question I asked here:

现在,我想问的正确方法清除/在一个结构数组空的元素。根据给出的解决方案,我想只是抵消在结构中的一个的[]数组。例如:

Now, I would like to ask the proper way to clear/empty an element in a struct array. According to solution given, I tried to just nullify the the a[] array in the struct. eg

 struct mystruct
 {
   char a[10];
   int b;
 };  // semi-colon added!

 struct mystruct array[20] =
 { 
   { "test1", 1 },  // character strings!
   { "test2", 2 },
   { "test3", 3 },
 };
 int i;
 for (i=0 ; array[i].a[0] != '\0' ; i++){
    if ( array[i].b == 2 ){
       array[i].a[0] = '\0';
       break;
    }
 }
 for (i=0 ; array[i].a[0] != '\0' ; i++){
     printf("[%s] => %f\n", array[i].a, array[i].b);
 }

当我显示阵列中,只有第一项仍然存在。项目与其余B = 2 B = 3 都没有了。我在做什么错在这里?我只是想删除其 B == 1项。我应该使用一个memset的()办呢?谢谢

when I display the array , only first item remains. the rest of the items with b=2 and b=3 are gone. What am I doing wrong here? I just want to delete the entry whose b==1. Should I use a memset() to do it? thanks

推荐答案

这迭代标准是不是在你的第二个循环正确的:

This iteration criteria is not correct in your second loop:

 for (i=0 ; array[i].a[0] != '\0' ; i++)

由于您已设置数组[1] .A [0] =='\\ 0'你的第一个循环,你的第二个循环将它认为,当停止数组[1] .A [0] =='\\ 0'

Because you've set array[1].a[0] == '\0' in your first loop, your second loop will stop when it sees array[1].a[0] == '\0'.

您需要通过不是测试字符串的第一个字符的一些不同的方式来跟踪有效元素的数目。例如,你可以只在整个阵列上循环,只打印出有效的元素,这种方式:

You need to keep track of the number of valid elements by some different means than testing the first character of the string. For example, you could just loop over the entire array and only print out the valid elements this way:

 for (i=0 ; i < sizeof(array)/sizeof(array[0]) ; i++){

     if (array[i].a[0] == 0)  /* skip empty elements */
         continue;

     printf("[%s] => %f\n", array[i].a, array[i].b);
 }

这篇关于在结构数组清除的项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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