所以我有一个链表建立这样的:初始化错误误会......需要一些澄清
#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部分保留内存,或者我是否缺少某些东西。我如何初始化数组,以便可以为数组的任何元素中的信息赋值?
谢谢
杰森
好吧,如果我有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
假设内存分配给'graph-> adjList [k]',那么至少可以避免涉及不分配内存的问题。另外,不要强制转换'malloc'的返回值;铸造可以隐藏其他问题。 –