简体   繁体   中英

C: Inserting element into an array of structs

I have an array of structs where each array element is:

struct Item {
  int code;
  char * label;
};

The array itself is a global variable:

struct Item * ht[SIZE];

This is how I currently insert an item into the array:

void insert(int toadd, char *toput) {

   struct Item *item = (struct Item*) malloc(sizeof(struct Item));
   item->label = toput;  
   item->code = toadd;

   int hashIndex = 0; 

   //move in array until an empty or deleted cell
   while(ht[hashIndex] != NULL && ht[hashIndex]->code != -1) {
      //go to next cell
      ++hashIndex;

      //wrap around the table
      hashIndex %= SIZE;
   }

   ht[hashIndex] = item;
}

In another function, I call the insert method, followed with some printf statements to check what's going on:

insert(ctr, trimwhitespace(line2));
printf("\nAdding to ht: String: %s Integer: %d\n", trimwhitespace(line2), ctr);

for (int i = 0; i < SIZE; i++) {
    if (ht[i] != NULL)
    printf("\nThis is what's inside ht: String: %s Integer: %d\n", ht[i] -> label, ht[i] -> code);            
}

This is an example of the output:

Adding to ht: String: four Integer: 6

This is what's inside ht: String: four Integer: 0

This is what's inside ht: String: four Integer: 4

This is what's inside ht: String: four Integer: 5

This is what's inside ht: String: four Integer: 6

As you can see, the struct is being inserted multiple times, with different integer values.

I think this is unlikely to be an issue with the loops that the insert call is in, as the first print statement would also be printed multiple times if the insert call was being made multiple times. But I may be wrong.

How do I make sure that the insert method only inserts the struct once and not multiple times? Or does the problem lie elsewhere?

Turns out that adding an if statement right before my insert method call, to check whether the particular key was already inserted earlier, solved the problem, though this may not be the most ideal fix:

if (!containsKey(trimwhitespace(stringcopy3))) {           

      insert(ctr, trimwhitespace(stringcopy3));
      printf("\nAdding to ht: String: %s Integer: %d\n", trimwhitespace(stringcopy3), ctr);

}

I'm still not sure why multiple instances of the key were being inserted in the first place, but this is a temporary solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM