表示图形时下一个指针出错

Error with the next pointer while representing graph

我正在尝试用 c 来表示图形的邻接表。 我首先尝试只制作结构。 但是,每次我使用下一个指针遍历邻接表时,我都会收到以下错误

“->”的无效类型参数(有 'struct grnode')

从类型 'struct grnode'

分配给类型 'struct grnode *' 时不兼容的类型

我能够理解代码背后的逻辑。

struct grnode 
{
    long long num;
    struct grnode *next;
};

struct graph 
{
    long long v;
    long long e;
    struct grnode *adj;
};

struct graph *adjlistgr()
{
    long long i,x,y;
    struct grnode *temp;
    struct graph *g = (struct graph*)malloc(sizeof(struct graph));
    if (!g) {
        printf("memory error");
        return;
    }
    // here we scanf  the num of vertices and edges
    scanf("%lld %lld", &g->v, &g->e);
    g->adj = malloc(g->v*sizeof(struct grnode*));
    for (i = 0; i < g->v; i++)
    {           
        g->adj[i].num = i;
        g->adj[i]->next = g->adj[i];
    }
    for (i = 0; i < g->e;i++)
    {   // now we scan the edges
        scanf("%lld %lld", &x, &y);
        temp = (struct grnode*)malloc( sizeof( struct grnode*));
        temp->num = y;
        temp->next = g->adj[x];
        g->adj[x]->next = temp;
        temp = (struct grnode*)malloc( sizeof( struct grnode*));
        temp->num = y;
        temp->next = g->adj[y];
        g->adj[y]->next = temp;
    }
    return g;
} 
g->adj[i]->next

应该是

g->adj[i].next

adj[i] 已经是指针,因此无需使用 -> 运算符。到处修复同样的东西。

g->adj = malloc(g->v*sizeof(struct grnode*));

应该是

g->adj = malloc((g->v)*sizeof(struct grnode));

sizeof(struct grnode)

给出的结构分配内存

供您理解:

struct b
{
   int b;
};

struct a
{
   int a;
   struct b *ptr;
};

int main()
{
   struct a *p = malloc(sizeof(struct a));
   p->a = 10;
   p->ptr = malloc(sizeof(struct b) * 2);
   /* Now you have a pointer `ptr` which can hold 2 struct b */
   /* So the access should be like */

   p->ptr[0].b = 20; /* ptr[0] = *(ptr +0)  */ 
   p->ptr[1].b = 30; /* ptr[1] = *(ptr + 1) */
}