C 数组赋值更改第一个值
我想用自定义元素创建一个二进制堆,堆使用C 数组赋值更改第一个值,c,arrays,C,Arrays,我想用自定义元素创建一个二进制堆,堆使用struct Elem数组来存储数据。但是在插入之后,一些数据丢失,在本例中是键值 #include <stdlib.h> #include <stdio.h> #define DEFAULT_CAPACITY 16 #define VALS 10 const int values[VALS] = {1, 2, 3, 4, 7, 8, 9, 10, 14, 16}; typedef int (*compareFuncti
struct Elem
数组来存储数据。但是在插入之后,一些数据丢失,在本例中是键
值
#include <stdlib.h>
#include <stdio.h>
#define DEFAULT_CAPACITY 16
#define VALS 10
const int values[VALS] = {1, 2, 3, 4, 7, 8, 9, 10, 14, 16};
typedef int (*compareFunction)(const void *, const void *);
typedef struct Elem {
void *key;
void *value;
} Elem;
typedef struct Heap {
unsigned int size;
unsigned int capacity;
Elem **array;
compareFunction compare;
} Heap;
Heap *hpCreate(compareFunction compare)
{
Heap *heap;
heap = (struct Heap *) malloc(sizeof(struct Heap));
if (heap == NULL) return NULL;
if ((heap->array = (struct Elem **) malloc(0)) == NULL) {
free(heap);
return NULL;
}
heap->size = 0;
heap->capacity = DEFAULT_CAPACITY;
heap->compare = compare;
return heap;
}
Elem *hpCreateElem(void *key, void *value)
{
Elem *el;
el = (struct Elem *) malloc(sizeof(struct Elem));
if (el == NULL) return NULL;
el->key = key;
el->value = value;
return el;
}
void hpInsert(Heap *hp, void *key, void *value)
{
Elem *el, *par;
int pos;
pos = hp->size++;
el = hpCreateElem(key, value);
par = hp->array[pos/2];
while (pos > 1 && hp->compare(el->key, par->key) > 0) {
hp->array[pos] = hp->array[pos/2];
pos = pos/2;
par = hp->array[pos/2];
}
hp->array[pos] = el;
}
int compare_int_ptr(const void *ptr1, const void *ptr2)
{
int v1 = *((int *) ptr1);
int v2 = *((int *) ptr2);
if (v1 == v2)
return 0;
else
return (v1 > v2) ? 1 : -1;
}
int main()
{
Heap *hp;
Elem *el;
int i;
hp = hpCreate(compare_int_ptr);
for (i = 0; i < VALS; i++) {
hpInsert(hp, (void *) &values[i], (void *) &values[i]);
}
for (i = 0; i < VALS; i++) {
el = hp->array[i];
printf("%d\n", *((int *) el->key));
}
return 0;
}
由于您告诉容器您分配了默认容量元素,因此没有将二进制堆数组正确排序为
16 9 14 7 4 8 10 3 2 1
:
heap->capacity = DEFAULT_CAPACITY;
然后:
应该是
malloc(DEFAULT_CAPACITY * sizeof(Elem*))
该行:
par = hp->array[pos/2];
正在读取未初始化的对象 因为您告诉容器您分配了默认容量元素:
heap->capacity = DEFAULT_CAPACITY;
然后:
应该是
malloc(DEFAULT_CAPACITY * sizeof(Elem*))
该行:
par = hp->array[pos/2];
正在读取未初始化的对象 我假设
malloc(0)
和defaultcapacity 16
似乎是相互矛盾的。我不确定你想做什么,但我相信malloc(0)
不会让你达到目的。更糟糕的是,你的while状况也不好。我很确定你想要while(pos>0
),而不是while(pos>1
不知何故我把Heap
读作Hash
,我真的被代码在做什么搞糊涂了。我会假设malloc(0)
和默认容量16
似乎是相互矛盾的。我不确定你想做什么,但我相信malloc(0)
不会让你达到目的。除了不适,你的while条件也是错误的。你肯定想要while(pos>0
,而不是while(pos>1
不知怎的,我把Heap
读作Hash
,我真的被代码在做什么弄糊涂了。