我正在尝试在 C 中实现 extract_heap() 。我想通过函数传递变量
size
(堆的)作为指针。代码生成一些警告,如下所示:
extract_max.c: In function ‘max_heapify’:
extract_max.c:26:20: warning: passing argument 2 of ‘max_heapify’ from incompatible pointer type [-Wincompatible-pointer-types]
26 | max_heapify(arr, &new_size, largest);
| ^~~~~~~~~
| |
| int **
extract_max.c:6:33: note: expected ‘int *’ but argument is of type ‘int **’
6 | void max_heapify(int *arr, int *new_size, int i)
| ~~~~~^~~~~~~~
extract_max.c: In function ‘extract_max’:
extract_max.c:41:20: warning: passing argument 2 of ‘max_heapify’ from incompatible pointer type [-Wincompatible-pointer-types]
41 | max_heapify(arr, &size, 0);
| ^~~~~
| |
| int **
extract_max.c:6:33: note: expected ‘int *’ but argument is of type ‘int **’
6 | void max_heapify(int *arr, int *new_size, int i)
它也会被编译并产生错误的输出。如果我通过函数按值传递变量
size
,只需将 size
更改为 size-1
即可产生正确的输出:
printf("\nThe elements of the heap after extract_max are:\n");
for(int i=0; i<size-1; i++)
printf("%d ", arr[i]);
我正在分享用于复制输出的完整代码:
#include<stdio.h>
#include<stdlib.h>
void max_heapify(int *arr, int *new_size, int i)
{
int l = 2*i+1;
int r = 2*i+2;
int largest = i, temp;
if(l<*new_size && arr[largest]<arr[l])
largest = l;
if(r<*new_size && arr[largest]<arr[r])
largest = r;
if(largest != i)
{
temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
max_heapify(arr, &new_size, largest);
}
}
void extract_max(int *arr, int *size)
{
int max;
if(*size < 1)
printf("\nNo element in the heap !");
else
{
max = arr[0];
arr[0] = arr[*size-1];
*size = *size-1;
max_heapify(arr, &size, 0);
printf("\nThe extracted max elemnt is: %d", max);
}
}
int main()
{
int i;
int arr[] = {12, -8, 20, 2, 3, 89, 71, -6, 11, 10};
int size = 10;
//build_max heap
for(i=size/2-1; i>=0; i--)
max_heapify(arr, &size, i);
printf("The elements of the heap after max heapification are:\n");
for(int i=0; i<size; i++)
printf("%d ", arr[i]);
printf("\n");
extract_max(arr, &size);
printf("\nThe elements of the heap after extract_max are:\n");
for(int i=0; i<size; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
在函数定义中
void max_heapify(int *arr, int *new_size, int i)
new_size 是一个指针 (
int *
)
...
max_heapify(arr, &new_size, largest);
在这里,您使用
&
获取指向它的指针 - 因此,创建一个指针到指针 (int **
),而您只需要一个普通指针来进行调用。
如果变量已经是一个指针,请不要使其更具指针性,只需将其传递,如下所示:
max_heapify(arr, new_size, largest);
其他类似警告也类似。