简体   繁体   中英

Allocating memory for Heap with mallocs

I'm having problems declaring a new heap, empty, with max size "capacity".

Heap struct:

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 struct:

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

The function that I need to create the heap is declared like that, where the argument capacity is the heap capacity.

heap* new_heap(int capacity){

Function that insert elements in Heap:

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;
}

FATHER and ROOT is defined like that (I don't understand what that means, was pre-defined for the project too)

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

and bigger_than like this:

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

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

What malloc calls do I need to use? The function new_heap must allocate all memory necessary for the number of elements specified as argument capacity.

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;
}

The first malloc will make enough space for your heap structure. The second is for "vector" (as you called it) of pointers to elements, since these need to be stored in a separate spot in memory (based on your declaration of heap ). Together, this allocates all the memory you need for the heap. I'm assuming you'll also have a new_element function that will handle allocating the memory for an individual element for you whenever you want to add something to the heap .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM