dorothy
dorothy

Reputation: 1243

Clearing an item in a struct array

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);
 }

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

Upvotes: 0

Views: 183

Answers (2)

Joe Z
Joe Z

Reputation: 17936

This iteration criteria is not correct in your second loop:

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

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);
 }

Upvotes: 1

weisert
weisert

Reputation: 183

Last for loop:

for (i=0 ; i < 3 ; ++i){
    if(array[i].a[0] != '\0')
        printf("[%s] => %f\n", array[i].a, array[i].b);
}

Upvotes: 2

Related Questions