Home > database >  How do I iterate through an array of structs?
How do I iterate through an array of structs?

Time:12-05

I have this hashmap I want to implement.

typedef void * Data;

typedef struct {
    Data data;                  //Data pointer to the data
    char * key;                 //char pointer to the string key
} HashMapItem;

typedef struct hashmap {
    HashMapItem * items;        //items of the hashmaps
    size_t size;                //size of the hashmaps
    int count;                  //how many elements are in the hashmap
} HashMap;

I declare it like so:

HashMap * create_hashmap(size_t key_space){
    if(key_space == 0)
        return NULL;
    
    HashMap * hm = malloc(sizeof(HashMap));                                     //allocate memory to store hashmap
    hm->items = calloc(key_space, sizeof(HashMapItem));          //allocate memory to store every item inside the map, null it
    hm->size = key_space;                                                       //set sitze of hashmap
    hm->count = 0;                                                              //empty at the begining


    return hm;
}

When i try to iterate through it, it says that expression must have arithmetic or pointer type but has type "HashMapItem" even though i declare it as a pointer of HashMapItems

 if((hm->items)[index] != NULL)

Any idea?

CodePudding user response:

typedef void * Data;

Never hide pointers behind typedefs. It is a very, very bad practice.

How to iterate.

typedef struct {
    void *data;                  //Data pointer to the data
    char * key;                 //char pointer to the string key
} HashMapItem;

typedef struct hashmap {
    HashMapItem * items;        //items of the hashmaps
    size_t size;                //size of the hashmaps
    size_t count;                  //how many elements are in the hashmap
} HashMap;


void foo(HashMap *map)
{
    for(size_t i = 0; i < map -> count; i   )
    {
        puts(map -> items[i].key);
    }
}

PS count member should be also size_t

EDIT. Below is wrong as hm->items)[index] has type HashMapItem and it is not pointer. You cant compare it to NULL.

 if((hm->items)[index] != NULL)
  • Related