下面是创建一个有 2 个指针的链表的代码。正在创建(打印)链接列表,并且所有指针(上一个 + 下一个)都很好。但是,当我调用函数“copay”并将其值(指针)分配给“duplicate”时,我遇到了段错误,但如果我仅使用“copay”并且不将其分配给任何其他变量,则没有问题。
typedef struct node {
int data;
struct node *next;
struct node *prev;
} node;
void insert(node **head, int data) {
node *new = (struct node *)malloc(sizeof(node));
new->data = data;
new->next = NULL;
node *temp = *head;
if (!(temp)) {
*head = new;
new->prev = NULL;
// printf("\n return : %d",data);
return;
}
while (temp->next)
temp = temp->next;
temp->next = new;
new->prev = temp;
// printf("\n return : %d",data);
}
void print(node **head) {
node *temp = *head;
printf("\n");
while (temp) {
printf(" %d ->", temp->data);
temp = temp->next;
}
printf(" NULL\n");
}
node *copay(node **head) {
node *temp = *head;
return temp;
}
int main() {
node *head;
insert(&head, 1);
insert(&head, 3);
insert(&head, 5);
insert(&head, 7);
insert(&head, 9);
(head)->prev = (head)->next->next;
(head)->next->next->prev = (head)->next->next->next->next;
(head)->next->next->next->next->prev = (head)->next;
print(&head);
node *duplicate = copay(&head);
// print(&duplicate);
}
最佳答案
函数main()
中有一个非常简单的问题:
node *head;
head
已定义但未初始化。您必须将其初始化为 NULL
才能使 insert()
正常运行,否则您将出现未定义的行为。顺便说一句,将一个实际上将节点附加到列表的函数命名为 insert
会令人困惑。将此行更改为:
node *head = NULL;
我不明白你想用这些线来实现:
(head)->prev = (head)->next->next;
(head)->next->next->prev = (head)->next->next->next->next;
(head)->next->next->next->next->prev = (head)->next;
其余部分对我来说看起来不错。
关于c - C 中函数的指针返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30417112/