5

我在下面两条标记的行上收到错误为“'->'的无效类型参数”请建议如何更正

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

2 回答 2

7

的左参数->必须是一个指针。H->array[0]是一个结构,而不是指向结构的指针。因此,您应该使用.运算符来访问成员:

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

或将它们组合起来:

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

顺便说一句,在 C 中你不应该转换malloc(). malloc()返回void*,并且 C 自动将其强制转换为目标类型。如果您忘记#include声明malloc(),则演员表将取消您应该得到的警告。这在 C++ 中并非如此,但您通常应该更喜欢new而不是malloc()在 C++ 中。

于 2013-09-17T21:24:51.830 回答
1

下标隐式取消引用该array成员。如果array有类型struct arr *,则array[0]有类型struct arr(记住它a[i]等价于*(a + i));

于 2013-09-17T21:39:50.397 回答