【问题标题】:Why doesn't my code work when I write "G->Adj[i]" but works on writing "G->Adj+i" in graph implementation (Adjacency List).?为什么我的代码在我写“G->Adj[i]”但在图形实现(邻接表)中写“G->Adj+i”时不起作用。?
【发布时间】:2021-12-01 05:00:19
【问题描述】:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
struct Graph* GraphList();
struct Listnode
{
     int vertex;
     struct Listnode*next;
};
struct Graph
{
  int V;
  int E;
  struct Listnode *Adj;
};
void main()
{
    struct Graph *G=NULL;
    int i;
    struct Listnode *temp=NULL;
    printf("Program to Implement graph using Adjacency List\n");
    G=GraphList();
     for(i=0;i<G->V;i++)
     {
         temp=G->Adj+i;
         while((temp->next)!=(G->Adj+i))
            {
                printf("%d-->",temp->vertex);
                temp=temp->next;
            }
        printf("%d",temp->vertex);
        printf("\n");
     }
}
struct Graph* GraphList()
{
     int i,j,x,y;
     struct Listnode *t,*temp;
      struct Graph *G;
      G=(struct Graph*)malloc(sizeof(struct Graph));
      printf("Enter the no.of vertices and Edges respectively\n");
      scanf("%d %d",&G->V,&G->E);
      G->Adj=(struct Listnode*)malloc((sizeof(struct Listnode))*G->V);  //Undirected Graph
      for(i=0;i<G->V;i++)
      {
          (G->Adj+i)->vertex=i+1;
       (G->Adj+i)->next= (G->Adj+i);
      }
      for(i=0;i<G->V;i++)
      {
          t= (G->Adj+i);
          printf("Enter number of neigbouring nodes to node-%d  ",i+1);
          scanf("%d",&x);
          for(j=0;j<x;j++)
          {
          printf("Enter the vertex number-%d that is neighbour to node -%d  ",j+1,i+1);
              scanf("%d",&y);
              temp=(struct Listnode*)malloc(sizeof(struct Listnode));
              temp->vertex=y;
              temp->next= G->Adj+i;
              while(t->next!= (G->Adj+i))
                     t=t->next;
              t->next=temp;
          }
      }
      return G;
}

上面的代码工作正常,但是当我用“G->Adj[i]”替换“G->Adj+i”时它不起作用。我创建了“struct Listnode”类型的数组(比如说size-5)并将其存储在“G->Adj”中,我觉得使用“G->Adj[i]”是公平的,但我没有不明白为什么会弹出错误信息:

"D:\DataStructures by SS\Graph Link (standard).c|60|error: incompatible types when assigning to type 'struct Listnode *' from type 'struct Listnode'| ".

请解释一下。

【问题讨论】:

  • 也许你需要有一个Adj 的双指针,比如struct Listnode **Adj;。所以它将是一个指向Listnodes 的动态指针数组。
  • 第60行是哪一个?
  • G-&gt;Adj[i]返回元素,但需要元素的地址,可以使用&amp;G-&gt;Adj[i]获取

标签: c data-structures graph adjacency-list


【解决方案1】:

G-&gt;Adj+i 等价于&amp;G-&gt;Adj[i]。要撤消 [i] 的取消引用,需要前导 & 号。

【讨论】:

  • 非常感谢@JohnKugleman。
猜你喜欢
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
相关资源
最近更新 更多