Home > database >  How to find the size of a key/value dictionary in C
How to find the size of a key/value dictionary in C

Time:10-16

I am very new to C and I am learning to use structs and pointers but I can't seem to figure out what I am doing wrong here. So I'm trying to find the size of a dictionary that resets every time the main function is called. When I try to run the code manually it would say segmentation fault. There are 2 files that is tested, one is with structs of the dictionary and all the functions and one is with the main. Any help would be greatly appreciated.

my code in the dict file:

size_t dict_size (const dict_t* dict) {
  dict_list_t* el = dict->head;
  size_t dict_ct = 0;

  while(el){
    dict_ct  ;
    el = el->next;
  }
  return dict_ct;

}

and the code in the main file:

else if(strncmp(cmd, "siz", 3) == 0) {
       size_t* size =(size_t*) dict_size(dict);
       printf("%ld\n", *size);
    }

CodePudding user response:

dict_size returns a size_t, not a size_t*. So using pointers here is wrong.

You want this:

if(strncmp(cmd, "siz", 3) == 0) {
       size_t size = dict_size(dict);
       printf("%zu\n", size);
    }

Bonus:

It's inefficient to calculate the dictionary size as you do. The dictionary size should be updated each time a new entry is addded and each time an entry is removed.

  • Related