c - 将堆作为参数传递
问题描述
我试图通过下面的代码创建几个将堆作为参数传递的函数。然而,结果并没有像我预期的那样。
#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
但相反,它什么也没打印。我也想过将它作为双指针传递,但我没有工作。这是否意味着我不能将堆作为参数传递(这意味着我必须将堆声明为全局变量)或者还有另一种方法可以做到这一点?
解决方案
您pushValue
的函数按值count
获取参数(这意味着函数接收数据的副本),因此它永远不会在函数中修改。相反,您应该作为指针传递,并且(因此)需要在函数内部取消引用它:main
count
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");
}
随时要求进一步澄清和/或解释。
推荐阅读
- microsoft-graph-api - Sharepoint 文件上传随机导致访问被拒绝错误
- function - 如何将函数的结果放入 Flutter 中的 Text 小部件中?
- reactjs - 如何强制 Apollo 客户端将缓存数据用于详细视图页面
- bash - 应用程序端出现“echo > /dev/tcp/localhost/8877”时的异常
- java - GSON - 在从 JSON 反序列化期间修剪字符串
- neo4j - 如何知道密码查询中是否发生超时?
- sql - 如何管理 COUNT、GROUP BY 和 HAVING?
- hadoop - Dataproc Worker Node 的磁盘利用率日益增加
- itk - 有没有办法在 vtk.js 中使用 interactiveStyleMPRSlice 获取当前索引或文件名?
- typescript - 动态方法重载取决于 TypeScript 中的枚举(可索引的方法签名而不是属性)