Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid type argument of ‘->’

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);
}
like image 779
Shashank Singh Avatar asked Sep 17 '13 21:09

Shashank Singh


2 Answers

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++.

like image 124
Barmar Avatar answered Nov 30 '22 21:11

Barmar


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

like image 36
John Bode Avatar answered Nov 30 '22 20:11

John Bode