C语言——编译时报错(error: invalid type argument of ‘->‘ (have ‘struct VexNode‘))

代码场景:

使用C语言访问结构体的成员变量时使用“->”报错


问题描述:

我想访问成员变量,为什么就报错了,真让人火大,完整代码如下:

#include <stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<stdbool.h>

#define MaxNodeNum 100
//弧
typedef struct ArcNode{
    int key; //指向的顶点
    struct ArcNode *next;  //指向下一条弧的指针
    int weight;  //边权值

}ArcNode;
//顶点向量
typedef struct VexNode{
    int val;
    ArcNode *first; //该顶点指向的第一条弧的指针

}VexNode,AdjList[MaxNodeNum];
typedef struct{
    AdjList adjList;
    int arcNum; //弧的数量
    int vexNum; //顶点的个数
}ALGraph;

bool CreateAdjTable(ALGraph *G,int arcNum,int vexNum)
{

    if(arcNum>MaxNodeNum || vexNum>MaxNodeNum){
        return false;
    }
    G->arcNum = arcNum;
    G->vexNum = vexNum;
    //给顶点向量赋值
    for(int i=0;i<vexNum;i++){
        G->adjList->val = i;
        G->adjList->first = NULL;
    }
    //添加弧到邻接表
    for(int i=0;i<arcNum;i++){
        int top;
        int tail;
        int weight;
        scanf("%d,%d,%d",&top,&tail,&weight);
        ArcNode *newArc = (ArcNode *)malloc(sizeof(ArcNode));
        newArc->key = top;
        newArc->next = G->adjList[i]->first;
        newArc->weight = weight;
        G->adjList->first = newArc;
    }
    printf("OK");
    return true;
}

int main(void){
    ALGraph *G;
    CreateAdjTable(G,3,4);
    printf("YES");
    return 0;
}

报错代码如下:

		newArc->key = top;
        newArc->next = G->adjList[i]->first;
        newArc->weight = weight;
        G->adjList->first = newArc;

图片
在这里插入图片描述
在这里插入图片描述


原因分析:

invalid type argument of ‘->’ (have ‘struct qstr_xid_element’)
这种错误一般是没有理解C中“->”与“.”用法的不同,“->”是指向结构体指针获取结构体的成员变量时所用,而“.”则是一般的结构体名获取结构体的成员变量时所用。简单来说,如果符号前是指针类型,那么用“->”,否则用“.”


解决方案:

newArc->next = G->adjList[i]->first;
这段代码改为newArc->next = G->adjList[i].first;
这样问题就解决啦!
在这里插入图片描述


版权声明:本文为qq_45870740原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。