supernova2706
supernova2706

Reputation: 29

Passing pointer to an array as a parameter to a function

I tried to build a heap and finally print the elements in the form of an array.

Here it is the code (I know this doesn't really make sense but I just wanted to test my knowlwdge of heap and dynamic arrays):

#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);
}

I'm getting 9 errors which are all the same

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

Upvotes: 0

Views: 61

Answers (2)

anastaciu
anastaciu

Reputation: 23792

The problem is the dereference of arr, across your funtions in multiple places, and the passing of dereferenced *arr in your functions to int * parameters, you should pass arr, try:

//...
void heapify(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])  //here
        largest = l;
    if (r <= n && arr[r] <= arr[i])  //here
        largest = r;
    if (largest != i)
    {
        int temp = arr[i];  //here
        arr[i] = arr[largest]; //here
        arr[largest] = temp; //here
    }
    heapify(arr, n, largest); //here
}
void buildh(int *arr, int n, int r, int c)
{
    int i;
    for (i = n / 2 - 1; i >= 0; i--)
        heapify(arr, n, i);    //here
    output(arr, r, c);         //here
}
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]); //here
        }
        printf("\n");
    }
}

int main()
{
    //...
    buildh(arr, n, r, c); //here
}

Upvotes: 0

Acorn
Acorn

Reputation: 26066

Your arr variable is of type pointer to int:

int *arr=malloc(n*sizeof(int));

So when you call buildh, which takes the same type, you have to pass it as-is:

buildh(arr,n,r,c);

Same for the other cases.

Upvotes: 1

Related Questions