首页 > 解决方案 > 将堆作为参数传递

问题描述

我试图通过下面的代码创建几个将堆作为参数传递的函数。然而,结果并没有像我预期的那样。

#include<stdio.h>

void upHeap_min2 (int *heap, int index)
{
    if (index == 0)
        return;

    int parentIdx = getParentIdx(index);
    if (heap[index] < heap[parentIdx])
    {
        int temp = heap[index];
        heap[index] = heap[parentIdx];
        heap[parentIdx] = temp; 

        upHeap_min2(heap, parentIdx);
    }
}

void pushValue (int *heap, int count, int value)
{
    count++;
    heap[count] = value;
    upHeap_min2(heap, count);   
}

void view(int *heap, int count)
{
    printf("Values inside heap: ");
    for (int i = 0; i < count; i++)
    {
        printf("%d ", heap[i]);
    }
    printf("\n");
}

int main()
{
    int heapDemo[101];
    int count = -1;
    pushValue(heapDemo, count, 30);
    pushValue(heapDemo, count, 20);
    pushValue(heapDemo, count, 40);
    pushValue(heapDemo, count, 90);
    pushValue(heapDemo, count, 10);

    view(heapDemo, count);

    return 0;
}

获取父索引的函数:

int getParentIdx (int index)
{
    return (index-1)/2;
}

上面的代码应该已经打印出来了

10 20 40 90 30

但相反,它什么也没打印。我也想过将它作为双指针传递,但我没有工作。这是否意味着我不能将堆作为参数传递(这意味着我必须将堆声明为全局变量)或者还有另一种方法可以做到这一点?

标签: carraysheap

解决方案


pushValue的函数按值count获取参数(这意味着函数接收数据的副本),因此它永远不会在函数中修改。相反,您应该作为指针传递,并且(因此)需要在函数内部取消引用它:maincount

void pushValue(int* heap, int* count, int value)
{
    ++(*count);
    heap[*count] = value;
    upHeap_min2(heap, *count);
}

然后,在 中main,您应该使用以下地址调用它:count

    pushValue(heapDemo, &count, 30); // And similarly for the other calls

此外,您的函数中的循环在view结束时停止。将循环限制更改为i <= count。(这个函数使用 count但不修改它,所以按值传递是可以的。):

void view(int* heap, int count)
{
    printf("Values inside heap: ");
    for (int i = 0; i <= count; i++) {
        printf("%d ", heap[i]);
    }
    printf("\n");
}

随时要求进一步澄清和/或解释。


推荐阅读