从结构数组中访问特定结构会产生分段错误

时间:2018-04-19 22:45:29

标签: c arrays pointers struct linked-list

我有一个由另一个结构类型的数组组成的结构。这是定义它们的代码

typedef struct linkedlist { // linked list of ints (for use in Node)
  int index;
  struct linkedlist *next;
} List;

typedef struct { // a Node of a Graph
  char *name;
  List *outlist; // adjacency list
  int outdegree; // length of outlist
  //double pagerank_score; //not needed for this exercise
} Node;

typedef struct {
  // your code goes here
  int MaxSize;
  Node *table;
} Graph;

Graph有一个节点数组

以下是一些使用这些结构的代码

int initialize_graph (Graph *mygraph, int MaxSize) 
{

  printf("initialise graph\n");
  // your code goes here
  mygraph = (Graph*) malloc(sizeof(Graph));
  mygraph->MaxSize = MaxSize;
  mygraph->table = (Node*) malloc(MaxSize * sizeof(Node));
  int i;
  for (i = 0; i<MaxSize; i++)
  {  
    mygraph->table[i].name = NULL;
    mygraph->table[i].outlist = NULL;
    mygraph->table[i].outdegree = 0;
  }
  for (i = 0; i<MaxSize; i++)
  {
    if (mygraph->table[i].outlist == NULL)
      printf("its null\n");
    else
      printf("aint null\n");
  }
  return 1;
}
int insert_graph_node (Graph *mygraph, int n, char *name) 
{
  printf("insert node %d\n", n );
  mygraph->table[n].name = (char*)malloc(sizeof(char)*20);
  strcpy(mygraph->table[n].name, name);
  return 1;
}

程序一进入insert_graph_node并使用

访问特定节点的名称
mygraph->table[n].name

程序因分段错误而停止。 我不知道为什么会这样,因为我做了初始化。

0 个答案:

没有答案