将指向数组的指针作为函数的参数传递

时间:2020-04-16 20:03:15

标签: c arrays pointers

我试图建立一个堆,最后以数组的形式打印元素。

这里是代码(我知道这没有什么意义,但我只想测试我的堆和动态数组知识)

#include <stdio.h>
#include <stdlib.h>
void heapiify(int *arr,int n, int i)
{
    int largest=i;
    int l=2*i+1;    // left node
    int r= 2*i+2;   // right node
    if(l<=n && *arr[l]>=*arr[i])
        largest=l;
    if (r <=n && *arr[r]<=*arr[i])
        largest= r;
    if(largest !=i)
    {
        int temp=*arr[i];
        *arr[i]=*arr[largest];
        *arr[largest]=temp;
    }
    heapify(*arr,n,largest);
}

void buildh(int *arr,int n,int r,int c)
{
    int i;
    for(i=n/2-1;i>=0;i--)
        heapify(*arr,n,i);
   output(*arr,r,c);
}

void output(int *arr,int r,int c)
{
    int i,j;
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
            printf("%d",*arr[i*c+j]);
        }
        printf("\n");
    }
}

int main()
{
    int i,j,r,c;

    printf("enter the number of rows");
    scanf("%d",&r);
    printf("enter the number of columns");
    scanf("%d",&c);

    int n=r*c;
    int *arr=malloc(n*sizeof(int));
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
            scanf("%d",&arr[i*c+j]);
    }

    buildh(*arr,n,r,c);
}

我遇到9个相同的错误

invalid argument type of unary '*'( have int)

2 个答案:

答案 0 :(得分:1)

您的{ 0: "cli/index.php", 1: "ttd/cache/reports", "e": true, "refresh-api": true, "s": "2020-04-16", "v": true } 变量的类型为指向arr的指针:

int

因此,当您调用int *arr=malloc(n*sizeof(int)); (具有相同类型)时,必须原样传递它:

buildh

与其他情况相同。

答案 1 :(得分:0)

问题是遍及您的函数在多个位置对arr的取消引用,以及将函数中已取消引用的*arr传递给int *参数,您应该传递{{1} },尝试:

arr