【发布时间】:2020-09-18 18:24:23
【问题描述】:
我尝试创建几个函数,通过下面的代码将堆作为参数传递。然而,结果并没有像我预期的那样。
#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
但它什么也没打印。我也想过将它作为双指针传递,但我没有工作。这是否意味着我不能将堆作为参数传递(这意味着我必须将堆声明为全局变量)还是有其他方法可以做到这一点?
【问题讨论】:
-
我很好奇你为什么不将
count作为指针传递给pushValue(heapDemo, count, 30);。我错过了什么吗?你不需要通过指针传递count,比如pushValue(heapDemo, &count, 30);