c - ‘->’ 的无效类型参数

标签 c pointers structure

我在以下两行标记的行中收到错误消息“'->' 的类型参数无效” 请建议如何更正它

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

最佳答案

-> 的左参数必须是一个指针。 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++ 中并非如此,但在 C++ 中,您通常应该更喜欢 new 而不是 malloc()

关于c - ‘->’ 的无效类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18860123/

相关文章:

c - 动态分配的结构体指针数组

c - 如何将结构体数组传递给 C 中的函数?

c++ - 传递结构错误 "unqualified-id before ' =' token"

c - 有符号整数的算术位移

c - Doxygen 不为全局函数生成文档

c++ - 当我们将指针从一个对象复制到同一类的另一个对象时,我们到底想要什么?

c - 将二维数组(矩阵)保存到 C 函数内的二进制文件

c - 实现搜索功能后二叉树段错误

c++ - Pro*C/C++ 是否支持 "describe [schema.]object"语句?

c++ - 结构成员的结构大小和地址