如何遍历结构体数组?HashMap遍历遇类型错误求助
HashMap遍历报错原因分析
问题背景
定义的HashMap结构体如下:
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;
创建HashMap的函数:
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 size of hashmap hm->count = 0; //empty at the beginning return hm; }
遍历时报错,报错代码:
if((hm->items)[index] != NULL)
错误提示:表达式必须具有算术或指针类型,但它的类型是"HashMapItem"
报错原因
- 类型不匹配:
hm->items是HashMapItem*类型,使用下标[index]访问时,得到的是一个HashMapItem结构体实例,而非指针。NULL是指针常量,只能和指针类型做比较,直接拿结构体对象和NULL对比,编译器会判定类型非法。 - 内存初始化逻辑:你用
calloc分配items内存时,会将每个HashMapItem的成员(data和key)初始化为0(对应指针类型就是NULL),所以要判断某个位置是否有有效元素,应该检查结构体内部的指针成员,而非结构体本身。
修正方法
把判断条件改成检查结构体的指针成员,比如:
// 检查key是否非空(或检查data,根据业务逻辑选择) if((hm->items)[index].key != NULL)
或者换一种更直观的写法:
HashMapItem *current_item = &hm->items[index]; if(current_item->key != NULL)
内容的提问来源于stack exchange,提问作者Cristian Cutitei
相关产品推荐
相关产品推荐

