使用malloc为堆分配内存

时间:2019-05-06 16:12:45

标签: c

我在声明一个新的空堆时遇到了问题,最大容量为“容量”。

堆结构:

typedef struct {
    /* number of elements on vector */
    int size;
    /* vector max size */
    int capacity;
    /*vector of pointers for elements*/
    element_t** elements;
} heap;

Element_t结构:

typedef struct element_
{
    char nameItem[100];
    char expirationDate[11];
    int qty;
    int sellRate;
    float priorityVal;
} element_t;

我需要创建堆的函数就是这样声明的,其中参数容量是堆容量。

heap* new_heap(int capacity){

在堆中插入元素的功能:

int heap_insert(heap *h, element_t* elem)
{
    element_t * aux;
    int i;
    //gilc
    if(!h) return 0;
    /* if heap is full, dont insert element */
    if (h->size >= h->capacity)
        return 0;

    if (!elem)
        return 0;

    /* insert element in the end of the heap */
    h->size++;
    i = h->size;
    h->elements[i] = elem;

    /* while element has more prioritary than his father, trade them */
    while (i != ROOT && bigger_than(h->elements[i], h->elements[FATHER(i)]))
    {
        aux = h->elements[FATHER(i)];
        h->elements[FATHER(i)] = h->elements[i];
        h->elements[i] = aux;
        i = FATHER(i);
    }
    return 1;

    //Default
    return 0;
}

“父亲和根”的定义是这样的(我不明白这是什么意思,也是为该项目预定义的)

#define FATHER(x)       (x/2)
#define ROOT        (1)

bigger_than像这样:

int bigger_than(element_t* e1, element_t* e2)
{
    if (e1 == NULL || e2 == NULL)
    {
        return 0;
    }

    return e1->priorityVal > e2->priorityVal;
}

我需要使用哪些malloc调用?函数new_heap必须为指定为参数容量的元素数量分配所有必需的内存。

1 个答案:

答案 0 :(得分:1)

heap *new_heap(int capacity) {
    heap *h = malloc(sizeof(heap));
    h->size = 0;
    h->capacity = capacity;
    h->elements = malloc(capacity * sizeof(element_t *));
    return h;
}

第一个malloc将为您的堆结构腾出足够的空间。第二个是指向元素的指针的“向量”(如您所说的),因为它们需要存储在内存中的单独位置(基于heap的声明)。这一起分配了堆所需的所有内存。我假设您还将有一个new_element函数,该函数将在您每次向heap添加内容时为您为单个元素分配内存。