gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:22:40 24 4
gpt4 key购买 nike

我正在尝试在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) */
}

关于c - 表示图形时下一个指针出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27936951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com