5

i am getting error as "invalid type argument of ‘->’ " on the below two marked lines please suggest how to correct it

#include<stdio.h>

struct arr{
    int distance;
    int vertex;
};

struct heap{
    struct arr * array;

     int count; //# of elements
     int capacity;// size of heap
     int heapType; // min heap or max heap
};


int main(){
    int i;
    struct heap * H=(struct heap *)malloc(sizeof(struct heap));
    H->array=(struct arr *)malloc(10*sizeof(struct arr));

    H->array[0]->distance=20;//error

    i=H->array[0]->distance;//error

    printf("%d",i);
}
Shashank Singh
  • 81
  • 1
  • 1
  • 5

2 Answers2

7

The left argument of -> must be a pointer. H->array[0] is a structure, not a pointer to a structure. So you should use the . operator to access a member:

H->array[0].distance = 20;
i = H->array[0].distance;

or combine them:

i = H->array[0].distance = 20;

BTW, in C you should not cast the result of malloc(). malloc() returns void*, and C automatically coerces this to the target type. If you forget to #include the declaration of malloc(), the cast will suppress the warning you should get. This isn't true in C++, but you usually should prefer new rather than malloc() in C++.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

The subscript implicitly dereferences the array member. If array has type struct arr *, then array[0] has type struct arr (remember that a[i] is equivalent to *(a + i));

John Bode
  • 119,563
  • 19
  • 122
  • 198