刚学到链表,代码构建十字链表的表头的时候直接运行不了了,错误内容俺刚开始学还看不明白。。
node* inithead(int row, int col, node* bighead[]) {
int i = 0;
node* term0 = (node*)malloc(sizeof(node));
bighead[0] = term0;
int headnum = row > col ? row : col;
for (i = 1; i < headnum; i++) {
bighead[i]= (node*)malloc(sizeof(node));
if (i == 1) {
bighead[0]->col = col;
bighead[0]->row = row;
bighead[0]->value = 0;
}
bighead[i - 1]->next = bighead[i];
bighead[i]->right = bighead[i];
bighead[i]->down = bighead[i];
}
bighead[headnum]->next = bighead[0];
return bighead[i];
}
就想问一下该怎么改才能顺利初始化,以及为什会这样。
(1)bighead[headnum]中的元素是未初始化的元素,bighead[headnum]->next = bighead[0];这么写会报错
(2)return bighead[i];这里,i等于headnum,bighead[i]也是未初始化的元素
(3)
bighead[i]->right = bighead[i];
bighead[i]->down = bighead[i];
这两句,本节点的right和down仍然是本节点吗?
(4)node结构体中,为什么用union?union中结构体和next共用内存,这么写不对吧。
修改成下面的试试,只修改了最后两句:
node* inithead(int row, int col, node* bighead[]) {
int i = 0;
node* term0 = (node*)malloc(sizeof(node));
bighead[0] = term0;
int headnum = row > col ? row : col;
for (i = 1; i < headnum; i++) {
bighead[i]= (node*)malloc(sizeof(node));
if (i == 1) {
bighead[0]->col = col;
bighead[0]->row = row;
bighead[0]->value = 0;
}
bighead[i - 1]->next = bighead[i];
bighead[i]->right = bighead[i];
bighead[i]->down = bighead[i];
}
bighead[headnum-1]->next = bighead[0]; //修改1 bighead[headnum]->next 改成 bighead[headnum-1]->next
return bighead[0]; //修改2 bighead[i]改成 bighead[0]
}
bighead[i]->right = bighead[i];
bighead[i]->down = bighead[i];
这啥意思,right和down都指向自己?
循环只到headnum-1,那么bighead[headnum]就是个空的,并没有malloc分配空间,自然bighead[headnum]->next就崩溃了