Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I iterate through an array of structs?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Any idea?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading