c - 使用 malloc 为堆分配内存

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

FATHER 和 ROOT 是这样定义的(我不明白这意味着什么,也是为项目预定义的)

#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 必须分配指定为参数容量的元素数量所需的所有内存。

最佳答案

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 将为您的堆结构腾出足够的空间。第二个是指向元素的指针的“vector ”(如您所说),因为这些需要存储在内存中的单独位置(基于您的 heap 声明)。总之,这会分配堆所需的所有内存。我假设您还会有一个 new_element每当您想向 heap 添加内容时,该函数都会为您分配单个元素的内存。 .

关于c - 使用 malloc 为堆分配内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56008886/

相关文章:

C - 等效于 .NET Console.ReadLine

c - 指针被部分篡改,为什么会这样以及如何调试?

c - 如何将 char* 分配给函数内的结构成员?

c - 海湾合作委员会警告: assignment makes integer from pointer without a cast

c - 为什么下面的程序可以运行

C:当所有类型相同时用不同的类型重新声明

C 错误 : "Called error is not a function or function pointer"

C文件操作: Check opened file pointer access mode

objective-c - 组合多个 y = mx + b 方程的最有效方法是什么?

c - 如何返回 C 中的列表?