地图包含-返回地图内部是否存在键。
mapPut-为特定键提供给定的值,并按顺序将其添加到地图中(如果键存在,则覆盖该值)。 mapRemove-删除一对键匹配给定元素的(键,数据)元素(通过键比较功能)。
mapGetFirst-将内部迭代器设置为地图中的第一个键,并返回它。
MapKeyElement mapGetFirst(Map map){
if(map == NULL){
return NULL;
}
if (map->head == NULL){
return NULL;
}
map->iterator = map->head;
return (map->copyMapKeyElements(map->iterator->key));
}
mapGetNext-将内部迭代器前进到下一个键,然后 返回它。
MapKeyElement mapGetNext(Map map){
if(map == NULL){
return NULL;
}
if((map->iterator->next)== NULL) {
return NULL;
}
map->iterator = map->iterator->next;
return (map->copyMapKeyElements(map->iterator->key));
}
typedef struct MapElements_t{
MapDataElement data;
MapKeyElement key;
struct MapElements_t* next;
} *MapElements;
struct Map_t{
copyMapDataElements copyMapDataElements;
copyMapKeyElements copyMapKeyElements;
freeMapDataElements freeMapDataElements;
freeMapKeyElements freeMapKeyElements;
compareMapKeyElements compareMapKeyElements;
MapElements head;
MapElements iterator;
};
/* ...... */
MapResult mapPut(Map map, MapKeyElement keyElement, MapDataElement dataElement) {
if ((map == NULL) || (keyElement == NULL) || (dataElement == NULL)) {
return MAP_NULL_ARGUMENT;
}
if (mapContains(map, keyElement)) {
mapRemove(map, keyElement);
}
MapElements new_map_element = malloc(sizeof(new_map_element));
if (new_map_element == NULL) {
return MAP_OUT_OF_MEMORY;
}
new_map_element->data = dataElement;
new_map_element->key = keyElement;
new_map_element->next = NULL;
if(map->head == NULL){
map->head = new_map_element;
map->iterator = map->head;
return MAP_SUCCESS;
}
mapGetFirst(map);
if (map->compareMapKeyElements(keyElement, map->iterator->key) < 0){
new_map_element->next = map->iterator;
map->head = new_map_element;
return MAP_SUCCESS;
}
while(map->iterator->next != NULL) {
if (map->compareMapKeyElements(keyElement, map->iterator->next->key) < 0) {
new_map_element->next = map->iterator->next;
map->iterator = new_map_element;
return MAP_SUCCESS;
}
mapGetNext(map);
}
map->iterator->next = new_map_element;
return MAP_SUCCESS;
}
答案 0 :(得分:1)
您有包含指针的typedef,例如typedef struct MapElements_t{...} *MapElements;
,它使类型MapElements
成为指针。
不建议这样做,原因如下:
完成时
MapElements new_map_element = malloc(sizeof(new_map_element));
您要分配的是指针的大小,而不是所指对象的大小。在您的情况下,您应该这样做:
MapElements new_map_element = malloc(sizeof(*new_map_element));
但最好您这样做:
typedef struct MapElements_t
{
//...
struct MapElements_t* next;
} MapElements;
因此您创建了一个指向事物的指针的变量,并明确地带有*
。
MapElements *new_map_element = malloc(sizeof(*new_map_element));
答案 1 :(得分:0)
问题出在这里;我必须替换此代码:
new_map_element->data = dataElement;
new_map_element->key = keyElement;
使用以下代码:
new_map_element->data = map->copyMapDataElements(dataElement);
new_map_element->key = map->copyMapKeyElements(keyElement);