2013-10-01 23 views
0

所以我有一个链表建立这样的:初始化错误误会......需要一些澄清

#define MAX 20 
//structure for a single linked list 
typedef struct element { 
    int info; 
    struct element *link; 
} Tnode; 

//structure for a grapgh 
typedef struct graphAdjList { 
    int nodes; 
    Tnode *adjList[MAX]; 
} Tgraph; 

在我的代码我有它设置如下:

Tgraph *graph; 

graph = (Tgraph*) malloc(sizeof(Tgraph)); 
graph -> nodes = 0; 

for(i; i < 20; i++){ 

    graph->adjList[i]= NULL; 
} 

graph->adjList[2]->info = 222; 

现在,如果我编译这我在这最后一行得到访问冲突。是否我没有为结构的Tnode部分保留内存,或者我是否缺少某些东西。我如何初始化数组,以便可以为数组的任何元素中的信息赋值?

谢谢

杰森

回答

1

你说得对,问题在于你没有为adjList中的单个节点分配内存。

当你做graph->adjList[2]->info = 222;时,graph->adjList[2]仍然是for循环之前的NULL

要解决这个问题,你需要为它第一次分配内存,如下所示:

graph->adjList[2] = malloc(sizeof(TNode)); 

注:可以只是graph->adjList[i] = malloc(sizeof(Tnode));取代graph->adjList[i] = NULL;在for循环,但是,当您去可能是有用的分配为了记忆效率。

+0

好吧,如果我有Tnode * newnode,* tail = NULL,* head = NULL;然后newnode =(Tnode *)malloc(sizeof(Tnode)); \t \t \t newnode-> info = 1; \t \t \t newnode-> link = NULL; \t \t \t graph-> adjList [k] - > link = newnode;这会正确设置链接列表吗? – Xintaris

+0

假设内存分配给'graph-> adjList [k]',那么至少可以避免涉及不分配内存的问题。另外,不要强制转换'malloc'的返回值;铸造可以隐藏其他问题。 –

0

您需要更换

graph-> adjList [我] = NULL;

graph-> adjList [I] =(TNODE *)malloc的(的sizeof(TNODE));