我正在尝试在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;
}
答案 0 :(得分:0)
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) */
}